Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django api framework getting total pages available

Tags:

django

Is it possible to get how many pages an API request has available? For example, this is my response:

{
    "count": 44,
    "next": "http://localhost:8000/api/ingested_files/?page=2",
    "previous": null,
    "results": [
        {
            "id": 44,
....

I'm pulling 20 elements per page, so there should be 2 pages in total, but currently the way it's set up I can get next and previous, but there's no context as to what the total amount of pages is. Sure I could do some math and get how many possible pages using the count, but I imagine something like this would be native to the framework, no?

This is my view:

 class IngestedFileView(generics.ListAPIView):
    queryset = IngestedFile.objects.all()
    serializer_class = IngestedFileSerializer

This is my serializer:

class IngestedFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = IngestedFile
        fields = ('id', 'filename', 'ingested_date', 'progress', 'processed', 'processed_date', 'error')
like image 719
Stupid.Fat.Cat Avatar asked Dec 05 '16 23:12

Stupid.Fat.Cat


People also ask

Can we do pagination for data in REST framework?

REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data.

What is pagination Django?

Django provides high-level and low-level ways to help you manage paginated data – that is, data that's split across several pages, with “Previous/Next” links.

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.


1 Answers

You can create your own pagination serializer:

from django.conf import settings
from rest_framework import pagination
from rest_framework.response import Response


class YourPagination(pagination.PageNumberPagination):

    def get_paginated_response(self, data):
        return Response({
            'links': {
               'next': self.get_next_link(),
               'previous': self.get_previous_link()
            },
            'count': self.page.paginator.count,
            'total_pages': self.page.paginator.num_pages,
            'results': data
        })

In your configuration in settings.py you add YourPagination class as the Default Pagination Class.

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.pagination.YourPagination',
    'PAGE_SIZE': 20
}

References:

  • Custom Pagination
like image 179
Evans Murithi Avatar answered Sep 19 '22 23:09

Evans Murithi