-
[Django] Rest 프레임워크로 [PUT] API 만들기 (feat. api_view, serializer)파이썬/Django 2023. 1. 10. 19:26728x90반응형
PUT 메소드 만들기 - 객체 수정
categories/views.py
elif request.method == "PUT": serializer = CategorySerializer( category, # 수정할 카테고리 데이터를 가져온다 data=request.data, # 사용자가 보낸 데이터 partial=True, ) if serializer.is_valid(): # 데이터가 유효하다면 updated_category = serializer.save() # save를 요청하면 자동으로 serializer.py에 있는 update 메소드가 실행된다. return Response(CategorySerializer(updated_category).data) else: return Response(serializer.errors)
partial = True : 부분 수정 허용
결과
요약
serializer는 단순한 번역기(장고 디비 객체 -> json 객체 )
장고 프레임 워크는 serializer를 만들도록 도와줌
전체코드
📁 categories/veiws.py
from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.exceptions import NotFound from rest_framework.status import HTTP_204_NO_CONTENT from .models import Category from .serializers import CategorySerializer @api_view(["GET", "POST"]) def categories(request): if request.method == "GET": all_categories = Category.objects.all() serializer = CategorySerializer(all_categories, many=True) return Response(serializer.data) elif request.method == "POST": serializer = CategorySerializer(data=request.data) if serializer.is_valid(): new_category = serializer.save() return Response( CategorySerializer(new_category).data, ) else: return Response(serializer.errors) @api_view(["GET", "PUT", "DELETE"]) def category(request, pk): try: category = Category.objects.get(pk=pk) except Category.DoesNotExist: raise NotFound if request.method == "GET": serializer = CategorySerializer(category) return Response(serializer.data) elif request.method == "PUT": serializer = CategorySerializer( category, data=request.data, partial=True, ) if serializer.is_valid(): updated_category = serializer.save() return Response(CategorySerializer(updated_category).data) else: return Response(serializer.errors) elif request.method == "DELETE": category.delete() return Response(status=HTTP_204_NO_CONTENT)
📁 categories/serializers.py
from rest_framework import serializers from .models import Category class CategorySerializer(serializers.Serializer): pk = serializers.IntegerField(read_only=True) name = serializers.CharField( required=True, max_length=50, ) kind = serializers.ChoiceField( choices=Category.CategoryKindChoices.choices, ) created_at = serializers.DateTimeField(read_only=True) def create(self, validated_data): return Category.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get("name", instance.name) instance.kind = validated_data.get("kind", instance.kind) instance.save() return instance
📁 categories/urls.py
from django.urls import path from . import views urlpatterns = [ path("", views.categories), path("<int:pk>", views.category), ]
📁 config/urls.py
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("api/v1/rooms/", include("rooms.urls")), path("api/v1/categories/", include("categories.urls")), ]
LIST'파이썬 > Django' 카테고리의 다른 글
[Django] Model View Sets 사용하기 (0) 2023.01.12 [Django] APIView를 이용한 views.py 리팩토링 1 (0) 2023.01.11 [Django] Rest 프레임워크로 [POST] API 만들기 (feat. api_view, serializer) (0) 2023.01.09 [Django] Rest 프레임워크로 [GET] API 만들기 (feat. api_view, serializer) (0) 2023.01.08 [Django] 어드민 액션 추가하기, 필터 만들기 (0) 2023.01.07