zoukankan      html  css  js  c++  java
  • 0030 DRF框架开发(17 分页Pagination)

      DRF提供了分布支持

    1 全局分页

      DRF全局分页,只需要在配置文件中按以下方式配置就可以了。不需要代码更改。

    REST_FRAMEWORK = {
        'DEFAULT_PAGINATION_CLASS':  'rest_framework.pagination.PageNumberPagination',
        'PAGE_SIZE': 10  # 每页数目
    }
    

    2 自定义分页

      自定义分布主要是根据不同视图进行不同的分页处理。

      在GeneralTools下创建一个Paginations.py文件,专门用于该APP中所有用于自定义分页的类。

    from rest_framework.pagination import PageNumberPagination
    
    
    class SetPageSize5(PageNumberPagination):
        page_size = 5
        page_size_query_param = 'page_size'
    
    
    class SetPageSize10(PageNumberPagination):
        page_size = 10
        page_size_query_param = 'page_size'
    
    
    class SetPageSize15(PageNumberPagination):
        page_size = 15
        page_size_query_param = 'page_size'
    

      在视图中用pagination_class来引用上面自定义的类就可以了。代码如下:

    from rest_framework import filters
    from rest_framework.filters import OrderingFilter
    from GeneralTools.Paginations import SetPageSize5
    
    
    class SchoolViewSet(GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin,
                        mixins.RetrieveModelMixin, mixins.DestroyModelMixin):
        queryset = Schools.objects.all()
        serializer_class = SchoolsSerializer
        filter_backends = [OrderingFilter, filters.SearchFilter]
        search_fields = ('name',)
        ordering_fields = ('teacher_quantity', 'student_quantity', 'employment_rate')
        pagination_class = SetPageSize5
    

    3 在接口文档中找到SchoolViewSet接口的list方法,先测试全局分页,再测试自定义分页。效果如下:

  • 相关阅读:
    js数组合并
    火狐浏览器打开新标签不断刷新,怎么解决?
    python获取当前路径
    python模块os
    python模块sys
    python玩丢手绢问题,出局的顺序
    python list元素为dict时的排序
    利用等概率Rand5产生等概率Rand3(转)
    python垃圾回收机制(转)
    负数在计算机中如何表示?(转)
  • 原文地址:https://www.cnblogs.com/dorian/p/12383521.html
Copyright © 2011-2022 走看看