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返回结果
相关推荐
萧鼎3 小时前
Python 数据验证神器 Pydantic:数据解析与验证、设置管理、JSONSche、与ORM集成全搞定
开发语言·python
529宝宝起名网3 小时前
用 Python 开发名字字源查询工具:从甲骨文到楷书的字形演变与文化寓意解析
开发语言·python
代码调试师3 小时前
【毕设分享】springboot攀枝花生鲜电商平台58990
java·vue.js·spring boot·后端·架构·eclipse·课程设计
2601_962300473 小时前
学习Python 爬虫路线
爬虫·python·学习路线·数据解析·反爬虫
隐擎fox3 小时前
跨越传输层防线:深入 TCP/IP 协议栈指纹(p0f)原理与 Python 原始套接字检测实战
python·网络协议·tcp/ip·网络安全·dns
洛阳泰山3 小时前
别卷 Python 了:我用 Java 21 + Spring Boot 3 打造了一个企业级 RAG + 智能体工作流引擎(附架构与源码解析)
java·spring boot·后端
午彦琳4 小时前
2026.9.11
数据结构·python·算法
新时代牛马4 小时前
ATF/ TEE / REE 与ARM 异常级别EL 安全体系完整篇:TrustZone硬件到 SMC 进OP-TEE的全链路
arm开发·python·安全
寥落半伤感4 小时前
在Pycharm中一键迅速安装包及查看虚拟环境中包名的方法
ide·python·pycharm
呆呆在发呆.4 小时前
Agnet狼人杀
人工智能·python·microsoft