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返回结果
相关推荐
zhangchaoxies几秒前
c++怎么在Linux下获取文件被最后一次访问的精确纳秒时间【进阶】
jvm·数据库·python
拾-光2 分钟前
LTX-Video 2.3 实战:用图片生成视频,消费级显卡也能跑的开源 I2V 模型(GPT Image 2)
java·人工智能·python·深度学习·算法·机器学习·音视频
m0_747854522 分钟前
c++怎么在Linux下获取文件被最后一次访问的精确纳秒时间【进阶】
jvm·数据库·python
AVA洋3 分钟前
初识Coze(扣子)工作流,ai视频自动化制作
人工智能·python·大模型
2301_816660214 分钟前
如何用HTML函数工具检测当前设备性能_内置诊断操作【操作】
jvm·数据库·python
zhangchaoxies14 分钟前
CSS如何实现移动端视口适配_利用rem与vw单位构建响应式布局
jvm·数据库·python
曲幽19 分钟前
FastAPI 文件上传避坑全指南:分块存盘、类型校验与安全兜底
python·upload·fastapi·web·file·chunk·validate·filetype
SilentSamsara19 分钟前
Python 基本语法:变量、数据类型与 print 的秘密
vscode·python·pycharm
m0_7478545223 分钟前
如何创建CDB公共用户_C##前缀强制规则与CONTAINER=ALL
jvm·数据库·python
Absurd58725 分钟前
SQL如何高效提取每组首条记录 ROW_NUMBER优化策略
jvm·数据库·python