Django Rest API分页在几页中填充相同的条目

时间:2018-03-30 02:25:06

标签: django django-rest-framework

我创建了一个带有分页功能的API,它有点工作,但唯一奇怪的是让我说声明只有10个条目将显示在1页,对于几个页面(例如:1-3)它填充相同的条目和少于10个条目,但当我打开第4页时,它填充下一个条目也少于10,然后同样的事情发生,直到我打开到第8页,任何人都可以告诉我为什么会发生这个错误。

继承我的API:

class ModelAFilterAPI(APIView):
    def get(self, request, project_id, search_type="", format=None):
        print(search_type)
        search_type_list_split = search_type.split('_')
        search_type_list = list(map(int, search_type_list_split))
        model_object = ModelA.objects.filter(project=project_id, id__in=search_type_list)
        paginator = Paginator(model_object, 10)
        page = request.GET.get('page')
        try:
            model_object = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            model_object = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            model_object = paginator.page(paginator.num_pages)
        serializer = ModelASerializer(model_object, many=True)
        return Response(serializer.data)

1 个答案:

答案 0 :(得分:0)

试试这个:

from rest_framework.pagination import PageNumberPagination


    class FilterApiPagination(PageNumberPagination):
        '''Get Boards Pagination'''
        page_size = 20

        def get_paginated_response(self, data):
            return Response(OrderedDict([
                ('next', self.get_next_link()),
                ('previous', self.get_previous_link()),
                ('results', data)
            ]))

    class ModelAFilterAPI(generics.ListAPIView):
          serializer_class = ModelASerializer
          pagination_class = FilterApiPagination
        def get(self, request, project_id, search_type="", format=None):
            print(search_type)
            search_type_list_split = search_type.split('_')
            search_type_list = list(map(int, search_type_list_split))
            model_object = ModelA.objects.filter(project=project_id, id__in=search_type_list)
        return Response({'data': model_object})