【问题标题】:How to Add JSON Array to DRF Response如何将 JSON 数组添加到 DRF 响应
【发布时间】:2020-02-13 21:53:56
【问题描述】:

我有一个返回这个的 DRF ListAPIView:

count: 35652
next: "https://platform/events/?format=json&page=2"
previous: null
results: (50) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
__proto__: Object

我需要向视图或序列化程序添加什么来返回它?

count: 35652
next: "https://platform/events/?format=json&page=2"
previous: null
results: (50) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
filter_data: ['filter element 1', 'filter element 2']
__proto__: Object

【问题讨论】:

    标签: python django-rest-framework


    【解决方案1】:

    由于您使用 ListAPIView,您可以覆盖 list() 方法,请记住,此方法需要返回一个 Response 对象(在源代码中也是 take a look)(受 this SO answer 启发)。

       def list(self, request, *args, **kwargs):
            response = super().list(request, args, kwargs)
    
            # you can add the data that you need in the response
            response.data['filter_data'] = ['filter element 1', 'filter element 2']
    
            return response
    

    另外,don't forget .data 包含已经序列化的数据。

    【讨论】:

      猜你喜欢
      • 2016-07-30
      • 2017-04-24
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多