I have a simple subclass of viewsets.ViewSet
which looks like:
from rest_framework import viewsets
from rest_framework.response import Response
from ..models import Entry, Sitting, Source, Venue
from .serializers import (
SittingSerializer, SittingWithEntriesSerializer,
)
class SittingViewSet(viewsets.ViewSet):
def list(self, request, version=None):
queryset = Sitting.objects.order_by('id')
serializer = SittingSerializer(
queryset, many=True, context={'request': request}
)
return Response(serializer.data)
def retrieve(self, request, pk=None, version=None):
prefetch_qs = Entry.objects.select_related('speaker')
queryset = Sitting.objects.order_by('id') \
.prefetch_related(Prefetch('entry_set', queryset=prefetch_qs))
sitting = get_object_or_404(queryset, pk=pk)
serializer = SittingWithEntriesSerializer(
sitting, context={'request': request}
)
return Response(serializer.data)
However, the list view isn't paginated, as it is if you use a subclass of ModelViewSet
. The settings I'm using are:
# Django Rest Framework settings:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('pombola.api.permissions.ReadOnly',),
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning',
'PAGE_SIZE': 10,
}
The documentation suggests looking at the source code for the mixins.ListModelMixin and generics.GenericAPIView classes, but I can't easily see how to reapply what they do to paginate results to these ViewSet methods.
Could anyone suggest what the simplest way would be to change this example to get pagination for the list
view?
You overrided the list method, so it doesnt paginate your data.
If you check
ListModelMixins
I think this might be your answer:Although this comes late as an answer, I wrote a Q&A style example for Django Rest Framework which enables non generic viewsets to have pagination.
By default, only the
viewsets.GenericViewSet
has automatic pagination (if you enable pagination in your settings of course), because it inherits fromgenerics.GenericAPIView
.That leaves you with 2 options:
The easy way:
mixins.ListModelMixin
provides pagination, so you can simply declare your viewset as follows:and you now have a
list()
method with pagination.The harder way: *
You can follow the example given above and create a pagination method inside your viewset.
The
list()
code must be derived from the source code of themixins.ListModelMixin
provided above.The
paginator()
,paginate_queryset()
andget_paginated_response()
methods can be copied from the Documentation or the source code of [generics.GenericApiView
][4]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, }
**Pagination in DRF using APIView and if you don't have serializer class **
Here I have used the django paginator, it is very simple