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返回结果
相关推荐
深蓝电商API26 分钟前
多线程 vs 异步 vs 多进程爬虫性能对比
爬虫·python
进击的雷神1 小时前
相对路径拼接、TEL前缀清洗、多链接过滤、毫秒级延迟控制——日本东京塑料展爬虫四大技术难关攻克纪实
爬虫·python
云溪·1 小时前
Milvus向量数据库混合检索召回案例
python·ai·milvus
柒.梧.1 小时前
Java集合核心知识点深度解析:数组与集合区别、ArrayList原理及线程安全问题
java·开发语言·python
AsDuang1 小时前
Python 3.12 MagicMethods - 49 - __imatmul__
开发语言·python
小湘西2 小时前
拓扑排序(Topological Sort)
python·设计模式
用户7344028193422 小时前
SpringBoot —— 实现邮件、短信的发送功能
后端
北京地铁1号线2 小时前
快手面试题:全局解释器锁
python·gil
写Cpp的小黑黑2 小时前
WebRTC建立流程详解 - 基于WHEP协议
后端