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返回结果
相关推荐
邋遢道8 分钟前
# 企业级 Agent 从 0 到 1(三):推理循环——让模型自己决定停,它就停不下来
人工智能·python
ZGG00310 分钟前
MCP 02:MCP 的各类比对——和 Function Calling、A2A、Skill 到底什么关系
人工智能·后端·python
IT_陈寒11 分钟前
Vite热更新突然失效?可能是这个配置在捣鬼
前端·人工智能·后端
dllmayday18 分钟前
基于python-can仿真生成blf
python
Steve__evetS30 分钟前
我的开源项目:python依赖安全修复助手
python·安全·agent
iNeuOS工业互联网1 小时前
多模态知识库,打通文本、图像与视频资源的协同实践与应用
人工智能·python·音视频
一晌小贪欢1 小时前
python-第20天:关键字参数与不定长参数
java·开发语言·前端·python·数据可视化·函数参数·python办公
BYSJMG1 小时前
计算机毕设选题|基于大数据与文本挖掘的自动驾驶事故成因分析及可视化研究|Hadoop+PySpark+Django+Vue
大数据·hadoop·信息可视化·django·自动驾驶·kmeans·课程设计
Metaphor6921 小时前
如何在 Python 环境中裁剪 PDF 页面
python·pdf
半亩码田1 小时前
C#转Python第4.4篇:JSON 处理:json 模块 vs System.Text.Json
python·c#·json