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返回结果
相关推荐
程序员天天困6 小时前
RustFS 1.0.0 深度解析:GA 之后,它值得替代 MinIO 吗?
后端·云原生·rust
葡萄城技术团队6 小时前
GcExcel V9.2 新特性揭秘:注音文字,随正文一起进 PDF
后端
海阔天空3676 小时前
1538 万行大表从 SQL Server 搬到 MySQL:一个支持断点续传的迁移工具设计与踩坑实录
后端
梦想不只是梦与想6 小时前
环境管理系统:Conda(一)
python·conda·环境隔离
狗头大军之江苏分军6 小时前
《潮水漫过十七岁》爸爸最近很忙
后端
isfox6 小时前
MapReduce Join 操作:大表关联小表用 Map 端,大表关联大表用 Reduce 端
后端
计算机源码社6 小时前
基于K-Means聚类的新生儿败血症临床分型与可视化分析系统 基于数据挖掘的新生儿败血症生命体征时序走势与关联性可视化研究
大数据·hadoop·python·数据挖掘·数据分析·spark·毕业设计
怕浪猫6 小时前
构建你自己的 AI Agent 发行版:从 Profile 定制到生产部署全流程
前端·后端·面试
一阵寒风6 小时前
用 AI 把PCB制前工程CAM无人值守输出系统做出来
python·ai编程·pcb工艺
SamChan907 小时前
Python 处理小语种 PDF 的编码坑:重音字符、连字与 (cid:xx) 乱码的解决方案
python·ai·pdf·机器翻译