在Django / REST中,如何(如果可能的话)将自定义字段添加到分页响应中?

snvhrwxg  于 2023-05-30  发布在  Go
关注(0)|答案(4)|浏览(160)

假设我有一个如下的视图:

class FooView(ListAPIView):
    serializer_class = FooSerializer
    pagination_class = FooPagination

它返回一个典型的分页响应,例如:

{
     "count":2,
     "next":null,
     "previous":null,
     "results":[
      {
          "id":1,"name":"Josh"
       },
      {
          "id":2,"name":"Vicky"
      }]
}

如何(如果可能的话)将自定义字段添加到此响应中,以使结果如下所示?

{
    "count":2,
    "next":null,
    "previous":null,
    "custom":"some value",
    "results":[
    {
         "id":1,"name":"Josh"
     },
     {
         "id":2,"name":"Vicky"
      }]
}

假设“某个值”以适当的方法计算并存储,例如:

def get_queryset(self):
    self.custom = get_custom_value(self)
    # etc...
cqoc49vn

cqoc49vn1#

另一个可能的解决方案是在响应中添加自定义字段,不需要重写Pagination类

def list(self, request, *args, **kwargs):
        response = super(YourClass, self).list(request, args, kwargs)
        # Add data to response.data Example for your object:
        response.data['custom_fields'] = 10 # Or wherever you get this values from
        return response
zour9fqk

zour9fqk2#

您需要覆盖FooPagination类中的get_paginated_response(),以便在响应中添加自定义字段。
您可以执行以下操作:

class FooPagination(pagination.PageNumberPagination):

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('custom': some_value), # add the 'custom' field  
            ('results', data),            
        ]))
mkh04yzy

mkh04yzy3#

在Rahul Gupta的答案的修改版本中,我们可以更新get_paginated_response函数返回的数据,只需向OrderedDict添加一个自定义字段。这将保持超类方法的完整性,将来如果超方法发生任何新的更改,它将不会影响

class CustomFieldPageNumberPagination(pagination.PageNumberPagination):
       def get_paginated_response(self, data):
           paginated_response = super(CustomFieldPageNumberPagination, self).get_paginated_response(data=data)
           paginated_response.data['custom_field']=<custom_field_value>
           return paginated_response
vhipe2zx

vhipe2zx4#

class LimitOffsetPagination(_LimitOffsetPagination):

    def get_paginated_response(self, data, **kwargs):
    return Response(
        OrderedDict(
            [
                ("count", self.count),
                ("next", self.get_next_offset()),
                ("previous", self.get_previous_link()),
                ("data", data),
            ] + [(key, value) for key, value in kwargs.items()]
        ) 
        
    )

相关问题