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返回结果
相关推荐
腾讯云云开发几秒前
【你可能不知道的开发技巧】一行代码完成小程序的CloudBase鉴权登录
前端·后端·微信小程序
申阳6 分钟前
Day 21:03. 基于 SpringBoot4 开发后台管理系统-整合 SpringSecurity 完成登录功能
前端·后端·程序员
毕设源码-钟学长8 分钟前
【开题答辩全过程】以 基于Python爬虫的二手房信息爬取及分析为例,包含答辩的问题和答案
开发语言·爬虫·python
Swizard11 分钟前
告别 NDK 噩梦!用 Python + Chaquopy 在 Android 上 5 分钟跑通 Paddle AI 模型
python·ai·移动开发
深蓝海拓11 分钟前
用于优化和改进YOLO11的一些方法
人工智能·python·yolo·机器学习
啦哈拉哈16 分钟前
【Python】知识点零碎学习1
数据结构·python·算法
layman052816 分钟前
在python中受限于GIL,进程中只允许一个线程处于允许状态,多线程无法充分利用CPU多核
开发语言·python
捧 花18 分钟前
Go Web 开发流程
开发语言·后端·golang·restful·web·分层设计
多恩Stone18 分钟前
【3DV 进阶-10】Trellis 中的表示 SLat 理解(1)
人工智能·python·算法·3d·aigc
南猿北者19 分钟前
go语言基础语法
开发语言·后端·golang