Django Rest Framework:向分页ViewSet添加自定义字段

时间:2017-08-01 20:17:02

标签: django django-rest-framework

我有一个分页结果集,所以响应会像这样回复:

{
"count": 944,
"next": "http://api.visitorlando.teeny/consumer/listings/?page=3",
"previous": "http://api.visitorlando.teeny/consumer/listings/",
"results": [
 {...}]
}

我需要在Response中添加另一个自定义字段,如下所示:

{
"count": 944,
"custom_field": "test",
"next": "http://api.visitorlando.teeny/consumer/listings/?page=3",
"previous": "http://api.visitorlando.teeny/consumer/listings/",
"results": [
 {...}]
}

我在ViewSet中。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

您可以定义自定义分页类:

class CustomPagination(pagination.PageNumberPagination):
    def get_paginated_response(self, data):
        return Response({
            'links': {
               'next': self.get_next_link(),
               'previous': self.get_previous_link()
            },
            'count': self.page.paginator.count,
            'results': data,
            "custom_field": "test",
        })


class YourListView(generics.ListAPIView):
    pagination_class = CustomPagination

更多详情:custom-pagination