获取下一页而不是下一页 link django rest framework

get next page number instead of next page link django rest framework

我正在使用 django rest framework 但我遇到了这个问题分页 输出显示在下一页和上一页link 但我只想要页码

我的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'

我的views.py

from  .paginations import MMycustomPagination

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

简单输出

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

您可以重写分页 class 中的 get_paginated_response 方法来像在 docs 中那样处理它,但修改 nextprevious值:

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

假设您的 pagination.py 文件位于 project_folder/app_name/pagination.py。您可以通过将 REST_FRAMEWORK 变量中的键 DEFAULT_PAGINATION_CLASS 设置为:

来全局设置此自定义分页样式
REST_FRAMEWORK = {
    ... # other keys you may be using
    'DEFAULT_PAGINATION_CLASS': 'app_name.pagination.MycustomPagination',
    'PAGE_SIZE': 5
}

在您的 settings.py 文件中。如果您想手动将其添加到您的视图中,您可以像在 views.py 文件中所做的那样指定 pagination_class = MycustomPagination