Issue
I have a ViewSet like this one to list users' data:
class Foo(viewsets.ViewSet):
def list(self, request):
queryset = User.objects.all()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
I want to turn on pagination like the default pagination for ModelViewSet:
{
"count": 55,
"next": "http://myUrl/?page=2",
"previous": null,
"results": [{...},{...},...,{...}]
}
The official doc says:
Pagination is only performed automatically if you're using the generic views or viewsets
...but my resultset is not paginated at all. How can I paginate it?
Solution
Pagination is only performed automatically if you're using the generic views or viewsets
The first roadblock is translating the docs to english. What they intended to convey is that you desire a generic viewset. The generic viewsets extend from generic ApiViews which have extra class methods for paginating querysets and responses.
Additionally, you're providing your own list
method, but the default pagination process is actually handled by the mixin:
class ListModelMixin(object):
"""
List a queryset.
"""
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 easy solution, use the framework code:
class Foo(mixins.ListModelMixin, viewsets.GenericViewSet):
queryset = User.objects.all()
serializer = UserSerializer
The more complex solution would be if you need a custom list
method, then you should write it as you see fit but in the style of the above mixin code snippet.
Answered By - Mark Galloway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.