覆盖列表方法打破了分页

时间:2018-04-20 07:57:59

标签: django django-rest-framework

我有这个ListAPIView:

class ProgramsHistory(ListAPIView):
    serializer_class = ProgramsHistoryItemSerializer
    paginate_by = 5

我需要在列表视图中添加额外的项目,并且我重写了这样的列表方法:

def list(self, request, *args, **kwargs):
    queryset = self.filter_queryset(self.get_queryset())
    serializer = self.get_serializer(queryset, many=True)
    response_list = serializer.data 
    response_list.append(some_value)
    return Response(response_list)

但是重写列表方法由于某种原因打破了分页。任何想法如何克服这个?

1 个答案:

答案 0 :(得分:1)

将您的列表代码更改为

def list(self, request, *args, **kwargs):
    queryset = self.filter_queryset(self.get_queryset())

    page = self.paginate_queryset(queryset)
    if page is not None:
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)

    serializer = self.get_serializer(queryset, many=True)
    response_list = serializer.data 
    response_list.append(some_value)
    return Response(response_list)