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返回结果
相关推荐
老蒋每日coding15 分钟前
Python:数字时代的“万能钥匙”
开发语言·python
甄心爱学习30 分钟前
KMP算法(小白理解)
开发语言·python·算法
培培说证44 分钟前
2026 高职计算机专业考证选择哪个更实用?
python
ASD123asfadxv1 小时前
LCD屏幕表面缺陷检测系统凹陷识别与定位技术分析
python
hanqunfeng1 小时前
(四十)SpringBoot 集成 Redis
spring boot·redis·后端
Ulyanov1 小时前
大规模战场数据与推演:性能优化与多视图布局实战
开发语言·python·性能优化·tkinter·pyvista·gui开发
tjjucheng1 小时前
小程序定制开发哪家口碑好
python
tjjucheng1 小时前
小程序定制开发源头厂家
python
过期的秋刀鱼!2 小时前
机器学习-带正则化的成本函数-
人工智能·python·深度学习·算法·机器学习·逻辑回归
郝学胜-神的一滴2 小时前
机器学习数据预处理:归一化与sklearn的MinMaxScaler详解
人工智能·python·程序人生·机器学习·性能优化·sklearn