Reputation: 141
So I recently switched over from using APIView to GenericAPIView - hoping this would give me access to more DRF features - pagination being one of them.
My understanding was that I could just add this setting globally and pagination would just work on all GenericAPIViews
settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 5
}
This does not enable pagination.
So then I also defined pagination_class as a class attribute
class job(GenericAPIView):
serializer_class = JobSerializer
pagination_class = PageNumberPaginator
def get_queryset(self):
return Job.objects.all()
def get(self, request, format=None):
queryset = self.get_queryset()
if queryset.exists():
serializer = JobSerializer(queryset, many=True)
return Response(serializer.data)
else:
return Response({"Returned empty queryset"}, status=status.HTTP_404_NOT_FOUND)
Still no pagination. This endpoint is returning over 100 records and adding string queries for ?page=1 or ?page=2 just returns the same 100+ list.
What am I doing wrong here? I understand that I can just copy the DRF's paginator view methods inside my class - but I thought using GenericAPIView allowed me to easily leverage the built in pagination?
Upvotes: 3
Views: 2295
Reputation: 46
in your views, first import PageNumberPagination
from rest_framework.pagination import PageNumberPagination
then write the following code
class LargeResultsSetPagination(PageNumberPagination):
page_size = 30
page_size_query_param = 'page_size'
max_page_size = 30
class PostsListAPIView(generics.ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
pagination_class = LargeResultsSetPagination
Upvotes: 0
Reputation: 1369
Instead of returning Response
object your should return self.get_paginated_response(...)
So the end of your code would be
return self.get_paginated_response(self.paginate_queryset(JobSerializer(queryset, many=True).data))
Upvotes: 1
Reputation: 308769
You could use ListAPIView
:
class Job(ListApiView):
serializer_class = JobSerializer
pagination_class = PageNumberPaginator
def get_queryset(self):
return Job.objects.all()
Upvotes: 3