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返回结果
相关推荐
象牙塔五六七20 分钟前
Java 泛型精讲:从 Stream 源码说起
后端
掘金挖土21 分钟前
前端手摸手跑路之 AI 应用开发(十二)
前端·后端
程序员cxuan22 分钟前
GPT-6.2 Astra 发布了,但口碑崩了。。。
人工智能·后端·程序员
象牙塔五六七23 分钟前
Java 函数式编程精讲:从 Stream 源码说起 —— 用真实源码学懂函数式思维
后端
字节跳动数据库37 分钟前
火山引擎缓存数据库:如何构建超大规模缓存集群的无感弹性能力
数据库·人工智能·后端
IT枫斗者枫哥39 分钟前
Java 异步导出只测最终行数,为什么下载时仍会少一行?
java·后端
用户78506119579740 分钟前
不会前端,我靠 AI 和 Python 做了一个 4K 壁纸站
后端
噜噜学上位机40 分钟前
什么是多态?
后端
站大爷IP44 分钟前
Python的类方法把我坑惨了,原来@classmethod和@staticmethod的区别这么大
后端
2401_868534781 小时前
逻辑网络设计
网络·python