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

drf框架重写分页paginate_queryset

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

解决当page超出范围时报错而不是返回一个空列表的问题:
代码:

from rest_framework.pagination import PageNumberPagination
from collections import OrderedDict
from rest_framework.response import Response
from django.core.paginator import InvalidPage
from rest_framework.exceptions import NotFound



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

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


    def paginate_queryset(self, queryset, request, view=None):
        """
        Paginate a queryset if required, either returning a
        page object, or `None` if pagination is not configured for this view.
        """
        empty = True

        page_size = self.get_page_size(request)
        if not page_size:
            return None

        paginator = self.django_paginator_class(queryset, page_size)
        page_number = request.query_params.get(self.page_query_param, 1)
        if page_number in self.last_page_strings:
            page_number = paginator.num_pages

        try:
            self.page = paginator.page(page_number)
        except InvalidPage as exc:

            # msg = self.invalid_page_message.format(
            #     page_number=page_number, message=str(exc)
            # )
            # raise NotFound(msg)
            empty = False
            pass

        if paginator.num_pages > 1 and self.template is not None:
            # The browsable API should display pagination controls.
            self.display_page_controls = True

        self.request = request

        if not empty:
            self.page = []

        return list(self.page)

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count if self.page else 0),
            # ('next', self.get_next_link()),
            # ('previous', self.get_previous_link()),
            ('code', 0),
            ('message', 'Ok'),
            ('results', data),
        ]))

视图:

    def list(self, request, *args, **kwargs):
        """返回面料规格"""
        # 筛选
        search = request.query_params.get("search", None)
        start_time = request.query_params.get('start_time', None)
        end_time = request.query_params.get('end_time', None)

        q_filter = Q()
        if search:
            q_filter.add(Q(name__icontains=search), Q.OR)

        conn = {'is_delete':False}
        if start_time and end_time:
            start_time = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
            end_time = datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
            conn['create_time__range'] = (start_time, end_time)

        # 查询
        queryset = Store.objects.filter(q_filter, **conn).select_related('user').order_by('-id')

        # 分页
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            data = {"store_data": serializer.data}
            return self.get_paginated_response(data=data)

        serializer = self.get_serializer(queryset, many=True)
        data = {'store_data': serializer.data}

        return APIResponse.success(data=data)
相关标签: Django