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?
Try providing a class variable
Create a Custom
ViewSet
which performs onlylist
operation as your case for here currently.Now inherit your class
Foo
with this custom made viewsetThis should help you get the pagination working.
For those using DRF 3.1 or higher, they are changing the default way pagination is handled. See http://www.django-rest-framework.org/topics/3.1-announcement/ for details.
Now if you want to enable pagination for a ModelViewSet you can either do it globally by setting in your settings.py file:
Or if you just want it for one ModelViewSet you can manually set the pagination_class for just that viewset.
This also allows you to tweak the way the pagination is handled for just that viewset.
DRF 3.1 also has introduced new types of default pagination schemes that you can use such as LimitOffset and Cursor.
A slightly simpler variation on this answer if you want pagination for a particular
ViewSet
, but don't need to customize the page size:Pagination in DRF using viewsets and list
Here I have handled a exception If page is empty it will show empty records
In setting define the page size, this page size is global and it is used by paginator_queryset in view
REST_FRAMEWORK = { 'PAGE_SIZE': 10, }
In view from rest_framework import mixins, viewsets
**> Note: If you not use Order_by it will show exception because this list
gives unordered list.**
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:The easy solution, use the framework code:
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.