[Fixed]-Difference between ViewSet and GenericViewSet in Django rest framework

27👍

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.

1👍

just inherit also from GenericViewSet.
For example:

#views.py
class PolicyViewSet(viewsets.ViewSet, 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)

1👍

From the django rest-framework source code:

class ViewSet(ViewSetMixin, views.APIView):
    """
    The base ViewSet class does not provide any actions by default.
    """
    pass


class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
    """
    The GenericViewSet class does not provide any actions by default,
    but does include the base set of generic view behavior, such as
    the `get_object` and `get_queryset` methods.
    """
    pass

class GenericAPIView(views.APIView):
    """
    Base class for all other generic views.
    """

The APIView does not contains the pagination it is implemented inside GenericAPIView

To use pagination inside ViewSet you should set the pagination class and follow the source code of GenericAPIView

The GenericAPIView contain the additional code which make it more structured. In case of usual cases GenericAPIView does the same task with less code. For complex scenarios when you want to customize more GenericAPIView would not provide any additional advantage.

0👍

How do i set up pagination with a normal Viewset?

If you want to use “pagination_class” in your viewset, so you should use GenericViewSet instead of ViewSet.

Leave a comment