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返回结果
相关推荐
shenlongproxy23 分钟前
代理IP故障演练怎么做:注入怎么分档、恢复怎么判定
后端
知识搬运临时工23 分钟前
Kafka 发 1 GiB 数据,用户态 CPU 只花 0.016 秒,总耗时反而慢了 11%
后端·kafka
wt952724 分钟前
VMware 虚拟机磁盘扩容实战文档(Ubuntu 22.04 + LVM)
linux·后端
5233AI开发笔记24 分钟前
API 返回 429:先区分限速、并发和配额,再决定是否重试
python
databook24 分钟前
经常听到的透视表是干什么的?
python·数据分析·pandas
王中阳Go25 分钟前
预算给够了,时间花错了地方:三跳链路给了 27 秒,实际只用掉 9 秒
人工智能·后端·性能优化
用户3949950846329 分钟前
文件变了,inotify 为什么没反应
后端
陈随易35 分钟前
神级 Skill,让 AI 用 HTML 代替 Markdown 回复
前端·后端·程序员
Gopher_HBo35 分钟前
go tool trace 使用指南(Go 1.24)
后端
一条Go36 分钟前
能力套餐:菜单、权限、开通范围怎么拆成三层而不打架
后端·github·saas