Django分页功能的使用和自定义分装

1. 在settings中进行注册
python 复制代码
# drf配置
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    # 分页设置
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 2
}
2. 在utils/myPagination.py中根据业务要求自定义分页返回结果
python 复制代码
from collections import OrderedDict

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


class MyPageNumberPagination(PageNumberPagination):
    # 1. page_size_query_param默认为None,前端通过传入pagesize字段指定一页有多少数据
    page_size_query_param = 'pagesize'
    # 2. 限制最大页面数量,为了安全
    max_page_size = 100

    # 3. 重写响应值,根据前端想要的 响应字段
    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('page', self.page.number),
            ('pages', self.page.paginator.num_pages),
            ('lists', data)
        ]))
3. 在视图中使用
python 复制代码
from meiduo_admin.utils.myPagination import MyPageNumberPagination

class UsersView(ListAPIView):
    pagination_class = MyPageNumberPagination
    serializer_class = UsersSerialize
    # 获取queryset时需要进行排序否则会有报错提示
    queryset = models.User.objects.filter(is_staff=False).all().order_by('-date_joined')
4. 路由
python 复制代码
from meiduo_admin.user.user_views import UsersView

urlpatterns = [

    # 获取用户
    path('users/', UsersView.as_view()),
]
5. postman返回结果
相关推荐
red1giant_star6 小时前
Python根据文件后缀统计文件大小、找出文件位置(仿Everything)
后端·python
长大19886 小时前
每秒10万写入的订单系统:MySQL分库分表、缓冲设计、批量写入优化实战
后端
渐儿7 小时前
缓存一致性与分布式锁:工程踩坑全解
后端
雷欧力7 小时前
如何使用 Claude API?3 种接入方案实测,附完整代码(2026)
python·claude
长大19887 小时前
为什么我加了索引,查询反而更慢了?
后端
阿聪谈架构7 小时前
第08章:MCP 模型上下文协议(下)
人工智能·后端
浮游本尊7 小时前
巡检全链路实现拆解——从采集到上传、解析、分析与报告展示
后端
神仙别闹7 小时前
基于 Python 实现 BERT 的情感分析模型
开发语言·python·bert
南方的耳朵7 小时前
三云主机节点部署OVN与验证报告
后端
小强19887 小时前
MySQL到底用不用JOIN?——从执行计划、数据量、分库分表角度分析最佳实践
后端