Difference between ViewSet and GenericViewSet in Django rest framework

Amistad picture Amistad · Feb 15, 2019 · Viewed 7.9k times · Source

I have a Django rest framework GenericViewset for which I am trying to set up pagination as follows:

#settings.py
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 
         'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20
}

#views.py
class PolicyViewSet(viewsets.GenericViewSet):
    def list(self, request):
        queryset = Policy.objects.all()
        page = self.paginate_queryset(queryset)
        serializer = PolicySerializer(page, many=True)
        return self.get_paginated_response(serializer.data)

This works as expected.However, if i try to do the same with just a normal Viewset as follows:

#views.py
class PolicyViewSet(viewsets.ViewSet):
    def list(self, request):
        queryset = Policy.objects.all()
        page = self.paginate_queryset(queryset)
        serializer = PolicySerializer(page, many=True)
        return self.get_paginated_response(serializer.data)

I get an error stating:

'PolicyViewSet' object has no attribute 'paginate_queryset'

How do i set up pagination with a normal Viewset. What is the difference between a GenericViewset and Viewset in DRF ?

Answer

Manzurul Hoque Rumi picture Manzurul Hoque Rumi · Feb 15, 2019

Pagination is only performed automatically if you're using the generic views or viewsets

Read the docs

And to answer your second question What is the difference between a GenericViewset and Viewset in DRF

DRF has two main systems for handling views:

  1. APIView: This provides some handler methods, to handle the http verbs: get, post, put, patch, and delete.
  2. ViewSet: This is an abstraction over APIView, which provides actions as methods:

    • list: read only, returns multiple resources (http verb: get). Returns a list of dicts.
    • retrieve: read only, single resource (http verb: get, but will expect an id). Returns a single dict.
    • create: creates a new resource (http verb: post)
    • update/partial_update: edits a resource (http verbs: put/patch)
    • destroy: removes a resource (http verb: delete)
  3. GenericViewSet: There are many GenericViewSet, the most common being ModelViewSet. They inherit from GenericAPIView and have a full implementation of all of the actions: list, retrieve, destroy, updated, etc. Of course, you can also pick some of them, read the docs.