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返回结果
相关推荐
贾公子2 分钟前
检测结果怎么落库——表结构、状态机与三类对账
后端·mysql
用户7908600572612 分钟前
我让 AI 自己上了趟网:browser-use 的三个致命坑和 CDP 混合方案
python
安枳杦14 分钟前
把一个 FastAPI 网页塞进 macOS 的 Dock:Tauri 2 + PyInstaller 实战
python
像风一样自由202015 分钟前
3.Dockerfile如何构建一个Python算法镜像
开发语言·人工智能·python·大模型
1360967572320 分钟前
LLM 当裁判可靠吗:位置偏见、长度偏见、自我偏好
后端
Dmz丶37 分钟前
前端转 AI 100 天 Day 36:Prompt 工程入门——从“感觉对了就行”到方法论
python
拖孩44 分钟前
流量主门槛从 500 降到 100,我的小程序上线 18 小时够到了线
前端·后端·微信小程序
养军博客1 小时前
Spring Security 4.x / 5.x / 6.x 配置全对比:前后端不分离与前后端分离
java·后端·spring·springsecurity
wifi___1 小时前
SpringBoot自动装配原理
java·spring boot·后端
日日大王学编程1 小时前
AI 时代后端方向新人的未来规划与看法
人工智能·后端·python·ai·golang