[Django]-Turn off automatic pagination of Django Rest Framework ModelViewSet

119👍

If you are using recent versions of DRF you just need to add pagination_class = None to your ModelViewSet definition.

class MyClassBasedView(ModelViewSet):
    pagination_class = None
    ...

You can also see some tips here https://github.com/tomchristie/django-rest-framework/issues/1390

15👍

ModelViewSet or mixins.ListModelMixin automatically create pagination for us. You can stop it by
paginator = None

class NotesViewSet(viewsets.ModelViewSet):    
     queryset = Notes.objects.all()
     serializer_class = NotesWriteSerializer
     paginator = None

5👍

And if you want paginator disabled for just one action:

@property
def paginator(self):
    self._paginator = super(NotesViewSet, self).paginator
    if self.action == 'the_action_you_want_pagination_disabled':
        self._paginator = None
    return self._paginator

use this in your ModelViewSet.

3👍

In settings.py for global

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': None,
    'PAGE_SIZE': 99999999, # a very large number
}

0👍

You can use a large number of items for specific view, keeping the results attribute and default pagination number for all others views, using a custom Pagination Class like this:

from rest_framework import pagination, permissions, viewsets


class FooViewSet(viewsets.ReadOnlyModelViewSet):
   class CustomFooPagination(pagination.PageNumberPagination):
      page_size = 10000

   pagination_class = CustomFooPagination
   queryset = FooModel.objects.filter(enabled=True)
   serializer_class = FooSerializer
   permission_classes = [permissions.IsAuthenticated]

👤Enoque

0👍

It can be done via two way either one you like or choose for you

Paginator Property

class MyClassBasedView(ModelViewSet):
    pagintor = None

Paginatior Class

class MyClassBasedView(ModelViewSet):
    pagination_class = None

Details about why we use methods

Reason of using these ways because the ModelViewSet class inherits GenericView that inherits GenericAPIView.

pagination class is a property of GenericAPIView that can be used to set pagination class or None for no pagination

Reference: https://github.com/encode/django-rest-framework/blob/aed7761a8d7e1691a4f4bbf9c83a447dac44d92a/rest_framework/generics.py#L158

paginator is also a property of GenericAPIView that can be used to set paginator class or None for no pagination

Reference: https://github.com/encode/django-rest-framework/blob/master/rest_framework/generics.py#L46

see the django rest framework code on Github

https://github.com/encode/django-rest-framework/blob/master/rest_framework/viewsets.py

Leave a comment