GenericAPIView로 만든 API를 ViewSet으로 리펙토링한다.
# urls.py
from django.urls import path
from api2 import views
urlpatterns = [
path('post/', views.PostListAPIView.as_view(), name='post-list'), #url 이름
path('post/<int:pk>', views.PostRetrieveListAPIView.as_view(), name='post-detail'),
path('comment/', views.CommentCreateAPIView.as_view(), name='comment-list'),
path('post/<int:pk>/like/', views.PostLikeAPIView.as_view(), name='post-like'),
path('catetag/', views.CateTagAPIView.as_view(), name='catetag'),
]
# urls.py
from django.urls import path
from api2 import views
urlpatterns = [
# PostViewSet
path('post/', views.PostViewSet.as_view(actions={'get': 'list'}), name='post-list'),
path('post/<int:pk>/like/', views.PostViewSet.as_view(actions={'get': 'like'}), name='post-like'),
# serializer_class가 달라서 그런지 위의 url과 묶여지지 않아서 pass함.
path('post/<int:pk>', views.PostRetrieveListAPIView.as_view(), name='post-detail'),
# CommentViewSet
path('comment/', views.CommentViewSet.as_view(actions={'post': 'create'}), name='comment-list'),
# category, tag 테이블을 다뤄야 하니 건들지 않는다.
path('catetag/', views.CateTagAPIView.as_view(), name='catetag'),
]
ViewSet은 actions 인자가 필수다. Router를 사용한다면 자동으로 actions 인자를 채워주지만 router를 사용하지 않을거니 추가해준다.
# views.py
class PostListAPIView(ListAPIView):
queryset = Post.objects.all()
serializer_class = PostListSerializer
pagination_class = PostPageNumberPagination
def get_serializer_context(self):
return {
'request': None,
'format': self.format_kwarg,
'view': self
}
class PostLikeAPIView(GenericAPIView):
queryset = Post.objects.all()
def get(self, request, *args, **kwargs):
instance = self.get_object()
instance.like += 1
instance.save()
return Response(instance.like)
class CommentCreateAPIView(CreateAPIView):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
# views.py
class PostViewSet(ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostListSerializer
pagination_class = PostPageNumberPagination
def get_serializer_context(self):
return {
'request': None,
'format': self.format_kwarg,
'view': self
}
# ViewSet에서는 get 메서드를 사용하지 않아서 like로 변경
def like(self, request, *args, **kwargs):
instance = self.get_object()
instance.like += 1
instance.save()
return Response(instance.like)
class CommentViewSet(ModelViewSet):
queryset = Comment.objects.all()
serializer_class = CommentSerializer