欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

drf框架自定义分页

程序员文章站 2022-07-12 10:34:34
...

drf 框架自定义分页

  1. 重写PageNumberPagination
from rest_framework.pagination import PageNumberPagination
from collections import OrderedDict
from rest_framework.response import Response


class StandardResultsSetPagination(PageNumberPagination):
    """全局的分页类,所有的list请求会调用"""

    page_size = 10  # 每页显示的条数
    page_size_query_param = 'page_size'  # 前端发送的页数关键字名
    max_page_size = 20  # 每页最大显示的条数

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('code', 0),
            ('message', 'Ok'),
            ('results', data),
        ]))
  1. 视图中如何使用
    def list(self, request, *args, **kwargs):
        """返回面料推荐模块中的数据"""
        recommend_model_id = request.query_params.get('recommend_model_id')
        # 查询
        queryset = RecommendFabric.objects.filter(recommend_model_id=recommend_model_id).select_related(
            'fabrics', 'recommend_model').order_by('-sequence', '-id')

        # 分页
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            data = serializer.data

            data = {"data": data}
            return self.get_paginated_response(data=data)

        # 未分页
        serializer = self.get_serializer(queryset, many=True)
        data = serializer.data

        data = {"data": data}
        return APIResponse.success(data=data)
  1. setting中的设置
REST_FRAMEWORK = {
    # 异常处理
    # 'EXCEPTION_HANDLER': 'one_fashion.utils.exceptions.exception_handler',
    # 认证
    'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework_jwt.authentication.JSONWebTokenAuthentication',  # 增加JWT认证
            'rest_framework.authentication.SessionAuthentication',
            'rest_framework.authentication.BasicAuthentication',
        ),
    # 分页配置
    'DEFAULT_PAGINATION_CLASS': 'one_fashion.utils.pagination.StandardResultsSetPagination',
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema',
    # 分页配置(后台)
    # 'DEFAULT_PAGINATION_CLASS': 'one_fashion.apps.management.page.CarPageNumberPagination',
    # 'PAGE_SIZE': 10,
    # 过滤配置
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}

  1. 分页结果
{
    "count": 3,
    "next": null,
    "previous": null,
    "code": 0,
    "message": "Ok",
    "results": {
        "data": [
            {
                "recommend_model_id": 12,
                "model_name": "很过分",
                "more_name": "发过火",
                "create_time": "2020-05-29T16:21:44",
                "category_name": "设计师推荐",
                "url": "",
                "category": 2
            },
            {
                "recommend_model_id": 11,
                "model_name": "官方",
                "more_name": "风格",
                "create_time": "2020-05-29T16:21:31",
                "category_name": "设计师推荐",
                "url": "",
                "category": 2
            },
            {
                "recommend_model_id": 3,
                "model_name": "设计师模块",
                "more_name": "更多",
                "create_time": "2020-04-30T12:01:10",
                "category_name": "设计师推荐",
                "url": "",
                "category": 2
            }
        ]
    }
}
相关标签: Django