为什么Pagination不适用于GenericAPIView?

时间:2018-05-08 18:25:13

标签: django django-rest-framework

views.py

class variable__list(ListAPIView):
    """

    get:
    returns a list of variable names

    """

    serializer_class = VariableSerializer
    pagination_class = PageNumberPagination
    page_size = 5

    def get_queryset(self):
        return Variable.objects.all()

    def get(self, request, format=None):
        # base queryset
        queryset = self.get_queryset()

        # return serialized data
        if queryset.exists():
            serializer = VariableSerializer(queryset, many=True)
            return Response(serializer.data)
        else:
            return Response({"Returned empty queryset"}, status=status.HTTP_404_NOT_FOUND)

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 5,
}

当我转到端点api / v1 / variable /?page = 1时, 我得到了100个结果返回的相同列表。我的理解是,当我在settings.py中全局设置分页时,这应该会自动生效,除此之外,我还在类级别定义了分页器,但仍然没有任何分页。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

删除getget_queryset方法,如果其中没有自定义逻辑。

class variable__list(ListAPIView):
    """

    get:
    returns a list of variable names

    """
    queryset = Variable.objects.all()
    serializer_class = VariableSerializer
    pagination_class = PageNumberPagination
    page_size = 5

如果您的内部有自定义代码,则需要手动发送分页响应

def get(self, request, format=None)

    paginator = PageNumberPagination()
    paginator.page_size = 10

    queryset = self.get_queryset()
    result_page = paginator.paginate_queryset(queryset, request)
    serializer = VariableSerializer(result_page, many=True)

    return paginator.get_paginated_response(serializer.data)