PostListAPIView
PostRetrieveAPIView
→ PostRetrieveAPIView는 Post에 대한 더 많은 정보를 담아서 내보내야 하므로, Serializer를 분리할 필요가 있음!
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from blog.models import Post, Comment
from .serializers import CommentSerializer, PostListSerializer, PostRetrieveSerializer
class PostListAPIView(ListAPIView):
queryset = Post.objects.all()
serializer_class = PostListSerializer
class PostRetrieveAPIView(RetrieveAPIView):
queryset = Post.objects.all()
serializer_class = PostRetrieveSerializer
class CommentCreateAPIView(CreateAPIView):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
from django.contrib.auth.models import User
from rest_framework import serializers
from blog.models import Post, Comment
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'is_staff']
class PostListSerializer(serializers.ModelSerializer):
class Meta:
model = Post
# fields = '__all__'
fields = ['id', 'title', 'image', 'like', 'category']
class PostRetrieveSerializer(serializers.ModelSerializer):
class Meta:
model = Post
# fields = '__all__'
exclude = ['create_dt']
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = '__all__'
# fields = ['id', 'title', 'image', 'like', 'category']
TODO
: category와 tags의 결과값이 pk값이 아닌 이름으로 나오도록 변경!
CreateModelMixin
클래스에 정의되어 있음
partial_update
와 update
메서드의 차이점kwargs['partial'] = True
로 해서 update 메서드를 호출함kwargs['partial'] = True
, kwargs['partial'] = False
차이!partial=partial
)하고 있음!# Update `comment` with partial data
serializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True)
partial=True
이면 모든 인자가 없더라도 partial update가 가능함!https://www.inflearn.com/course/%EC%9E%A5%EA%B3%A0-drf/dashboard