products 만들었어용
views 부분 구현~
from django.shortcuts import render
from django.http import JsonResponse,HttpResponse
from django.core import serializers
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
from .models import Product
from .serializers import ProductSerializer
@api_view(["GET","POST"]) # products 목록 조회
def products_list(request):
if request.method == 'GET':
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = ProductSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
# 예외 발생을 true 값으로 둠 -> 유효성 검사 통과하지 못하면 (serializer.errors,status=400) 내부적으로 실행
serializer.save() # 유효성 검사 통과하면 products 생성
return Response(serializer.data, status=status.HTTP_201_CREATED) # 201=created
@api_view(["GET", "PUT", "DELETE"]) # products 상세 조회, 수정, 삭제
def products_detail(request, pk):
if request.method == 'GET':
products = get_object_or_404(Product, pk=pk)
serializer = ProductSerializer(products)
return Response(serializer.data)
elif request.method == 'PUT':
products = get_object_or_404(Product, pk=pk)
serializer = ProductSerializer(products, data=request.data, partial=True)
# partial=True : 부분 수정 가능
if serializer.is_valid(raise_exception=True): # 유효성 검사 통과 못하면 error
serializer.save()
return Response(serializer.data) # 수정된 데이터 리턴
elif request.method == 'DELETE':
products = get_object_or_404(Product, pk=pk) # 지울 products 조회
products.delete()
return Response(status=status.HTTP_204_NO_CONTENT)