Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 237
Amistad Avatar asked Feb 07 '19 05:02

Amistad


People also ask

How does pagination work in Django REST framework?

Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView , you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the mixins. ListModelMixin and generics.

What is ViewSet in Django REST framework?

Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet . In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.

What is difference between APIView and ViewSet?

APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.

What is Paginator in Django?

Django provides a few classes that help you manage paginated data – that is, data that's split across several pages, with “Previous/Next” links. These classes live in django/core/paginator.py. For examples, see the Pagination topic guide.


1 Answers

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)
like image 129
Shakil Avatar answered Oct 15 '22 18:10

Shakil