awwester
awwester

Reputation: 10162

DRF pagination_class not returning paginating results

I'm trying to paginate the results of a ViewSet but can't get the response to paginate the data.

When I set a global pagination it works fine, however I don't want to do this and override all my views/viewsets that come from GenericAPIView, because I only want paginate on one class.

"""
don't want to do this, but this works showing that my view is based off of `GenericAPIView`.

# settings.py 
"""
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination'
}

When I remove the default setting, this view loses the paginated results

# views.py
from rest_framework.viewsets import ModelViewSet

class ClipViewSet(ModelViewSet):
    serializer_class = ClipSerializer
    queryset = Clip.objects.all()
    pagination_class = PageNumberPagination

From all indications in the docs this should be completely possible, and I'm not sure why in my project it's not working. I'm using django 1.9.7 and DRF 3.4.0

Upvotes: 4

Views: 2038

Answers (1)

Seb D.
Seb D.

Reputation: 5195

This is not a bug. As you can see in the source code, the default page size for PageNumberPagination is None, that means that the pagination is disabled, even if you explicitly indicated a paginator class.

You need to subclass PageNumberPagination with your required page_size to be able to activate pagination:

class MyPageNumberPagination(PageNumberPagination):
    page_size = 5

class ClipViewSet(ModelViewSet):
    pagination_class = MyPageNumberPagination

Please note you need to set page_size on the paginator class, not on the view.

Or put the page size in global settings:

REST_FRAMEWORK = {
    'PAGE_SIZE': 5
}

Then you can use directly PageNumberPagination.

Upvotes: 9

Related Questions