Reputation: 3496
I'm having a problem with Django Rest Framework's Pagination class.
Versions:
Here is my Custom pagination class.
pagination.py:
from rest_framework import pagination
class VideoPagination(pagination.PageNumberPagination):
page_size = 10
page_size_query_param = 'page'
max_page_size = 10000
settings.py:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': ('rest_framework.pagination.PageNumberPagination',),
'PAGE_SIZE': 10,
}
In my views.py, I have a ListAPIView that lists the all video models and it uses my custom paginator.
views.py:
class explore(ListAPIView):
serializer_class = ExploreVideoSerializer
pagination_class = VideoPagination
def get_queryset(self):
category = self.kwargs['category']
if category == 'all':
return Video.objects.all().order_by('-date')
else:
return Video.objects.filter(category=category).order_by('-date')
def get_serializer_context(self):
return {"request": self.request}
The problem is, When I make a request to this view, in first page it gives 10 items which is what I want. Then on the second page and third page, it gives less than 10 items.
For example, there are 16 video items. In the first request, it gives the first 10 of them. In the second page's request, it gives 2 of them. It also says there is another page and gives another 3 of them. In page 4, it gives 4 of them. What might be the reason for such behaviour? I couldn't fix it so that I'm asking for your help.
Not: In the first url, I do not add page number. next url is directly ?page=2. So i guess it is not using the ?page=1 but when I make a request for ?page=1 it gives only 1 model.
Upvotes: 2
Views: 2542
Reputation: 91
Another problem in the code is:
'DEFAULT_PAGINATION_CLASS': ('rest_framework.pagination.PageNumberPagination',),
should be:
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
Upvotes: 1
Reputation: 11439
The problem is page_size_query_param = 'page'
. Here you are saying that the page should be of size page
. So a URL with ?page=2
will give you a page_size
of 2.
What you want is page_query_param
. But its default is page
, so if you remove this line everything should work.
Upvotes: 5