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 分钟前
Kite:两种方式实现动态表名
java·后端
孤独风雪8 分钟前
Spring Stomp 消息使用
java·后端
间彧8 分钟前
ShardingSphere详解与SpringBoot实战分库分表指南
后端
掘金一周11 分钟前
2026 春晚魔术大揭秘:作为程序员,分分钟复刻一个 | 掘金一周 2.26
前端·人工智能·后端
Rabbit_QL11 分钟前
【BPE实战】从零实现 BPE 分词器:训练、编码与解码
python·算法·nlp
掘金者阿豪12 分钟前
Jenkins前端访问卡顿优化实战:从主题插件故障到性能调优全记录
后端
chainStriker12 分钟前
从零到上线:Python开源项目的规范化开发与发布指南
python·开源
掘金者阿豪12 分钟前
时序数据库国产化替代的“深水区”:金仓数据库如何重构物联网数据底座
后端
JavaGuide22 分钟前
微信面试:什么是一致性哈希算法?适用什么场景?
后端·面试
Charlie_lll25 分钟前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode