Nart Nart - 16 days ago 16
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

models
Office.py

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)


Serializer

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")


views.py

@api_view(["GET"])
@permission_classes((AllowAny,))
def offices(request):
instance = Office.objects.filter()[:10]
serializer = OfficeSerializer(instance, many=True)

return Response(serializer.data)


Any help with returning Office list with pagination ?

Answer

http://www.django-rest-framework.org/api-guide/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.

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py#L35 https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py#L166

so I would suggest something like:

@api_view(["GET"])
@permission_classes((AllowAny,))
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(serializer.data)