Home > Enterprise >  get next page number instead of next page link django rest framework
get next page number instead of next page link django rest framework

Time:05-04

I'm working with django rest framework but I face this problem with the pagination the output Show in next and previous the page link but I want the page number only

my pagination.py

from rest_framework.pagination import PageNumberPagination

class MycustomPagination(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'page_size'
    max_page_size = 10
    page_query_param = 'page'

my views.py

from  .paginations import MMycustomPagination

class AllSerialed(ListAPIView):
    pagination_class = MycustomPagination
    queryset = MyModel.objects.filter(blacklist=False).order_by("-date")
    serializer_class = MyModelSerial

simple output

{
    "count": 20,
    "next": "http://127.0.0.1:7000/data/?page=3",
    "previous": "http://127.0.0.1:7000/data/?page=1",
    "results": [
               ]
}

CodePudding user response:

You can override the get_paginated_response method in your pagination class to handle that like they do in the docs but modifying the next and previous values:

from rest_framework.pagination import PageNumberPagination

class MycustomPagination(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'page_size'
    max_page_size = 10
    page_query_param = 'page'

    def get_paginated_response(self, data):
        return Response({
            'next': self.page.next_page_number() if self.page.has_next() else None,
            'previous': self.page.previous_page_number() if self.page.has_previous() else None,
            'count': self.page.paginator.count,
            'results': data
        })

Let's think that your pagination.py file is located in project_folder/app_name/pagination.py. You can set this custom pagination style gloabally by setting the key DEFAULT_PAGINATION_CLASS in the REST_FRAMEWORK variable to:

REST_FRAMEWORK = {
    ... # other keys you may be using
    'DEFAULT_PAGINATION_CLASS': 'app_name.pagination.MycustomPagination',
    'PAGE_SIZE': 5
}

in your settings.py file. If you want to add it manually to your views you can specify pagination_class = MycustomPagination like you are already doing in your views.py file.

  • Related