django restframework에도 CBV를 가지고 있다.
rooms/urls.py
from django.urls import path
from . import views
app_name = "rooms"
urlpatterns = [path("list/", views.ListRoomsView.as_view())]
rooms/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Room
from .serializers import RoomSerializer
class ListRoomsView(APIView):
def get(self, request):
rooms = Room.objects.all()
serializer = RoomSerializer(rooms, many=True)
return Response(serializer.data)
이전에 했던 결과와 동일하다.
다만 차이점은, 예를 들어 인증 클래스 같은 걸 추가하고 싶을 때 생긴다.
우리는 APIView를 가지고 있다. 하지만 너무 많은 방들이 존재하고 있기 때문에 DB가 버벅거릴 수 있는 문제점이 있다.
다른 방안으로, Generic View 중의 하나로 ListAPIView라고 불리는 것이 있다.
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from .models import Room
from .serializers import RoomSerializer
class ListRoomsView(ListAPIView):
pass
이렇게 수정하면
위와 같은 에러가 나온다. queryset 속성을 포함하거나 get_queryset() method를 override하라는 소리다.
queryset을 추가하면
queryset = Room.objects.all()
또 다른 에러가 나온다.
serializer_class = RoomSerializer
위와 같이 추가한다.
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
config/settings.py에 위와 같이 추가한다.
결과