• Django分页功能的使用和自定义分装


    1. 在settings中进行注册
    1. # drf配置
    2. REST_FRAMEWORK = {
    3. 'DEFAULT_AUTHENTICATION_CLASSES': (
    4. # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    5. 'rest_framework_simplejwt.authentication.JWTAuthentication',
    6. 'rest_framework.authentication.SessionAuthentication',
    7. 'rest_framework.authentication.BasicAuthentication',
    8. ),
    9. # 分页设置
    10. 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    11. 'PAGE_SIZE': 2
    12. }
    2. 在utils/myPagination.py中根据业务要求自定义分页返回结果
    1. from collections import OrderedDict
    2. from rest_framework.pagination import PageNumberPagination
    3. from rest_framework.response import Response
    4. class MyPageNumberPagination(PageNumberPagination):
    5. # 1. page_size_query_param默认为None,前端通过传入pagesize字段指定一页有多少数据
    6. page_size_query_param = 'pagesize'
    7. # 2. 限制最大页面数量,为了安全
    8. max_page_size = 100
    9. # 3. 重写响应值,根据前端想要的 响应字段
    10. def get_paginated_response(self, data):
    11. return Response(OrderedDict([
    12. ('page', self.page.number),
    13. ('pages', self.page.paginator.num_pages),
    14. ('lists', data)
    15. ]))
    3. 在视图中使用
    1. from meiduo_admin.utils.myPagination import MyPageNumberPagination
    2. class UsersView(ListAPIView):
    3. pagination_class = MyPageNumberPagination
    4. serializer_class = UsersSerialize
    5. # 获取queryset时需要进行排序否则会有报错提示
    6. queryset = models.User.objects.filter(is_staff=False).all().order_by('-date_joined')
    4. 路由
    1. from meiduo_admin.user.user_views import UsersView
    2. urlpatterns = [
    3. # 获取用户
    4. path('users/', UsersView.as_view()),
    5. ]
    5. postman返回结果

  • 相关阅读:
    阿里云99元服务器2核2G3M带宽_4年396元_新老用户均可
    基于 Redis 实现接口限流
    智能家居的智能升级
    神经网络与深度学习笔记(1)——实践基础
    深入理解java垃圾回收机制
    Postman知识汇总
    Python飞机大战小游戏
    【C++】6-19 方阵的转置 分数 10
    C#解析JSON
    Pandas数据类型-DataFrame数据编辑
  • 原文地址:https://blog.csdn.net/qq_44906497/article/details/134030543