在REST框架中返回字典而不是数组 [英] Return dictionary instead of array in REST framework
问题描述
我正在将一组现有的API从tastypie转换为REST框架。默认情况下,在执行列表API时,stastepie返回包含对象列表的字典和元数据字典,其中REST框架仅返回对象数组。例如,我有一个名为Site的模型。 Tastypie返回的字典看起来像是
I am converting a set of existing APIs from tastypie to REST framework. By default when doing list APIs, tastypie returns a dictionary containing the list of objects and a dictionary of metadata, where REST framework just returns an array of objects. For example, I have a model called Site. Tastypie returns a dictionary that looks like
{
"meta":
{ ... some data here ...},
"site":
[
{... first site...},
{...second site...}
...
]
}
其中REST框架仅返回数组
where REST framework returns just the array
[
{... first site...},
{...second site...}
...
]
我们没有以任何方式使用好吃的元数据。在REST框架中更改返回值的最小侵入方法是什么?我可以重写list(),但我希望REST框架尽其所能。
We are not using the metadata from tastypie in any way. What is the least invasive way to change the return value in REST framework? I could override list(), but I would rather have REST framework do its thing where ever possible.
推荐答案
我认为您会必须重写 list()
方法。
I think you will have to override the list()
method.
我们首先得到原始回复。然后,使用 data
属性在响应上设置自定义表示,并使用此自定义表示返回响应。
We first get the original response. Then we set the custom representation on response using data
attribute and return response with this custom representation.
class MyModelViewSet(viewsets.ModelViewSet):
def list(self, request, *args, **kwargs):
response = super(MyModelViewSet, self).list(request, *args, **kwargs) # call the original 'list'
response.data = {"site": response.data} # customize the response data
return response # return response with this custom representation
这篇关于在REST框架中返回字典而不是数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!