Response pagination (not always performed)

146 views
Skip to first unread message

David Miranda

unread,
Oct 31, 2016, 3:43:27 PM10/31/16
to Django REST framework
Hi,

The pagination in my APIs (ModelViewSet) does not always work. Sometimes returns the paged results and sometimes not (the get_paginated_response method is not executed). I have the settings set pagination class and the PAGE_SIZE parameter. A
Thanks

Norbert Mate

unread,
Nov 2, 2016, 6:57:18 AM11/2/16
to Django REST framework
Hi,
  does this happen if the result size is smaller than the requested items per page? Example: you have 3 items in the db and from the frontend you request 10.

Regards,
Norbert.

David Miranda

unread,
Nov 2, 2016, 9:13:37 AM11/2/16
to Django REST framework
Yes! Any suspicion of what might be ?

Regards

Norbert Mate

unread,
Nov 2, 2016, 11:11:55 AM11/2/16
to Django REST framework
The problem might be that the generic views list method (like ListApiView) returns a list of objects it the page is None.

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

The problem might be in the default pagination class (in PageNumberPagination the page_size_query_param is set to None). To fix this I have created a custom pagination class:

Use it by overwriting the default pagination class:
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': ‘path.to.pagination.CustomPageNumberPagination',
}

Norbert Mate

unread,
Nov 2, 2016, 12:09:44 PM11/2/16
to Django REST framework
And don't forget to set the page_size query param when you are making the request or set the default page size in the settings:
'PAGE_SIZE': 10,

David Miranda

unread,
Nov 2, 2016, 12:19:04 PM11/2/16
to Django REST framework
I'm already using a custom pagination class. The problem is that when this happens the list method is not invoked.

Norbert Mate

unread,
Nov 2, 2016, 12:26:30 PM11/2/16
to Django REST framework
Then I would need more info to be able to try to help. Can you share some code?

David Miranda

unread,
Nov 2, 2016, 12:32:33 PM11/2/16
to Django REST framework
I recently introduced django cachalot (redis cache). Can be this?

Norbert Mate

unread,
Nov 3, 2016, 3:06:44 AM11/3/16
to Django REST framework
Disable it and check if the problem still persist.
Reply all
Reply to author
Forward
0 new messages