如何制作自己的分页Django

3hvapo4f  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(213)

我有一些来自第三方API的JSON数据,其中有3rd_party.com/API?NumberOfItemsOnPage=5&PageNumber1 NumberOfItemsOnPage -一个页面上有多少项和PageNumber -当前页面。这个json有项目,关于当前页面的信息,页面上有多少项目以及一般有多少页面
我想知道如何使用ListView类中的paginate_by在json中分页

class myView(ListView)

    paginate_by = 5

    def get_queryset(self, ...):
        queryset = []
        page_number = self.request.GET.get('page')

        # This might be wrong but I doesn't realy care because I need to know how to paginate using default django pagination
        request = f'3rd_party.com/API?NumberOfItemsOnPage=5&PageNumber{page_number}' 

        queryset = request.json()
        return queryset

我想我需要覆盖django分页器类,但我不知道如何做到这一点,因为django分页器分页将通过只有第一页,不会得到另一个的

oxiaedzo

oxiaedzo1#

在这里,您将找到官方文档:how to override pagination
就我而言,我遵循HackSoftware的风格指南:
为此,您需要创建函数get_paginated_response

from rest_framework.response import Response

def get_paginated_response(*, pagination_class, serializer_class, queryset, request, view):
    paginator = pagination_class()

    page = paginator.paginate_queryset(queryset, request, view=view)

    if page is not None:
        serializer = serializer_class(page, many=True)
        return paginator.get_paginated_response(serializer.data)

    serializer = serializer_class(queryset, many=True)

    return Response(data=serializer.data)

然后这样称呼它:

class UserListApi(ApiErrorsMixin, APIView):
    class Pagination(LimitOffsetPagination):
        default_limit = 1

    class OutputSerializer(serializers.Serializer):
        id = serializers.CharField()
        email = serializers.CharField()
        is_admin = serializers.BooleanField()

    def get(self, request):
        users = user_list()

        return get_paginated_response(
            pagination_class=self.Pagination,
            serializer_class=self.OutputSerializer,
            queryset=users,
            request=request,
            view=self
        )

相关问题