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 小时前
金仓数据库DISTINCT优化:从全表扫描到LIMIT 1的蜕变
后端
小马爱打代码6 小时前
Spring源码 第十二篇:Spring 全套核心原理 - 完结终章
java·后端·spring
西安邮电大学6 小时前
2026华为OD机考真题附答案-准备生日礼物
java·后端
Trouvaille ~6 小时前
【Redis篇】Hash 哈希:字段级操作与对象存储的最佳实践
数据库·redis·后端·算法·缓存·哈希算法·键值对
辞忧九千七6 小时前
吃透Redis7核心数据结构:从基础用法到实战场景(Python版)
开发语言·数据结构·redis·python
空圆小生6 小时前
基于 Python+Vue3 的 AI 人脸识别门禁考勤系统
开发语言·人工智能·python
Yoshizawa-Violet6 小时前
模板方法模式实战:重构Agent工具审批,告别重复代码
python·agent·模板方法
Rust研习社6 小时前
Nightly 前瞻:cargo-script 让 Rust 也能写脚本
后端·rust·编程语言
AskHarries6 小时前
Chrome 插件有没有机会
后端
浩风祭月6 小时前
一次诡异的 MySQL 死锁,靠 AI 分析日志十分钟定位根因
后端·ai编程