如何基于PageNumberPagination创建返回页码的自定义分页类?
问题修复点
你的原有代码主要存在三个问题:
- 没有按DRF分页类的规范配置查询参数映射,自定义的
page、page_item_count属性不会被框架自动识别 - 字段取值错误:
page.count是无效属性,你需要的总页数要从分页器实例获取 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
相关产品推荐
相关产品推荐

