Setting up pagination for list method in Django Rest framework viewset

I have a Viewset which has the following list method:

class PolicyViewSet(viewsets.ViewSet):
    def list(self, request):
        queryset = Policy.objects.all()
        serializer = PolicySerializer(queryset, many=True)
        return Response(serializer.data)

This works as intended and I get my desired Response.However, now I am trying to limit the objects returned per GET request and for that I am using pagination.I have defined the following in the settings.py:

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

The docs say:

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

However, my result is still not paginated.What else do I need to do to enable pagination ?

Answer

If you overwrite your list or any main method you need to explicitly called for that.

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)

Leave a Reply

Your email address will not be published. Required fields are marked *