Nart Nart - 7 months ago 197
Python Question

Django rest framework pagination with custom API view

I am trying to add pagination into my project, couldn't find any clear documentation or tutorial.

I have a list of offices


class Office(Model):
name = CharField(_("name"), default=None, max_length=255, null=True)
email = EmailField(_("email"), default=None, max_length=255, null=True)
description = TextField(_("description"), default=None, null=True)


class OfficeSerializer(ModelSerializer):
id = IntegerField(read_only=True)
name = CharField(read_only=True)
email = URLField(read_only=True)
description = CharField(read_only=True)

class Meta:
model = Office
fields = ("id", "name", "email", "description")

def offices(request):
instance = Office.objects.filter()[:10]
serializer = OfficeSerializer(instance, many=True)

return Response(

Any help with returning Office list with pagination ?


Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the mixins.ListModelMixin and generics.GenericAPIView classes for an example.

so I would suggest something like:

def offices(request):
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
    paginator = pagination_class()
    queryset = Office.objects.all()
    page = paginator.paginate_queryset(queryset, request)

    serializer = OfficeSerializer(page, many=True)

    return paginator.get_paginated_response(