You need to enable JavaScript to run this app. 如何基于PageNumberPagination创建返回页码的自定义分页类?
优惠活动
大模型
产品
解决方案
定价
更多

如何基于PageNumberPagination创建返回页码的自定义分页类?

问题修复点

你的原有代码主要存在三个问题:

  1. 没有按DRF分页类的规范配置查询参数映射,自定义的page、page_item_count属性不会被框架自动识别
  2. 字段取值错误:page.count是无效属性,你需要的总页数要从分页器实例获取
  3. result_count取值错误:len(data)只能拿到当前页数据条数,总数据条数需要从分页器获取

正确实现代码

from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

class CustomPagination(PageNumberPagination):
    # 配置页码查询参数名,对应你要的page参数
    page_query_param = "page"
    # 配置每页条数查询参数名,对应你要的page_item_count参数
    page_size_query_param = "page_item_count"
    # 未传page_item_count时的默认每页条数
    page_size = 10
    # 可选:限制每页最大条数,避免参数过大导致接口性能问题
    max_page_size = 200

    def get_paginated_response(self, data):
        page = self.page
        next_page = page.next_page_number() if page.has_next() else None
        previous_page = page.previous_page_number() if page.has_previous() else None

        return Response({
            # 总页数:总数据量/每页条数向上取整的结果
            "page_count": page.paginator.num_pages,
            # 总数据条数
            "result_count": page.paginator.count,
            "next": next_page,
            "previous": previous_page,
            "has_next_page": page.has_next(),
            "has_previous_page": page.has_previous(),
            "result": data,
        })

使用方法

在需要使用该分页规则的DRF视图中指定分页类即可:

from rest_framework import viewsets

class YourBusinessViewSet(viewsets.ModelViewSet):
    queryset = YourModel.objects.all()
    serializer_class = YourBusinessSerializer
    # 绑定自定义分页类
    pagination_class = CustomPagination

接口调用示例:GET /your/api/path/?page=3&page_item_count=15,即可获取第3页、每页15条的格式化返回结果。


内容的提问来源于stack exchange,提问作者sundowatch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 15:24:04