Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 223
Nart Avatar asked Oct 18 '16 16:10

Nart


People also ask

How do I Paginate in Django REST framework?

To enable this pagination style globally, you can set rest_framework. pagination. PageNumberPagination class to DEFAULT_PAGINATION_CLASS and also set the PAGE_SIZE as desired. You can open the settings.py file and add the below configuration settings.

Does pagination improve performance Django?

Additionally, switching to keyset pagination will improve the performance of page lookups and make them work in constant time. Django makes it easy to alter its default configuration, giving you the power to build a performant solution for pagination in Django.

Why pagination is not working in Django?

Your contexts aren't right and your templates call to the pagination follow the same way, so when you call the pagination object it will will not return a result as you did not use it in your queryset for loop.

Is Django GOOD FOR REST API?

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.


2 Answers

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)
like image 154
Michael Rigoni Avatar answered Oct 14 '22 06:10

Michael Rigoni


http://www.django-rest-framework.org/api-guide/pagination/

GET https://api.example.org/accounts/?limit=100&offset=400

Response:

HTTP 200 OK
{
    "count": 1023
    "next": "https://api.example.org/accounts/?limit=100&offset=500",
    "previous": "https://api.example.org/accounts/?limit=100&offset=300",
    "results": [
       …
    ]
}

Example of settings.py

REST_FRAMEWORK = {
    'PAGE_SIZE': 10,
    'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
    'DEFAULT_PAGINATION_CLASS':
        'rest_framework_json_api.pagination.PageNumberPagination',
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework_json_api.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework_json_api.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    )
}
like image 26
renno Avatar answered Oct 14 '22 06:10

renno