擅长:python、mysql、java
<p>@Michael Rigonis答案(<a href="https://stackoverflow.com/a/45238191/270265">https://stackoverflow.com/a/45238191/270265</a>)是成功的关键。我不得不对它稍加调整,所以我也可以将它用于顶级</p>
<pre><code>class DictSerializer(serializers.ListSerializer):
key = None
def __init__(self, *args, **kwargs):
self.key = kwargs.pop('key', self.key)
super().__init__(*args, **kwargs)
def to_representation(self, data):
r = super().to_representation(data)
return {item[self.key]: item for item in r}
@property
def data(self):
# This is a bit nasty, because the only "Many-Serializer" is a ListSerializer we inherit of it,
# but when converting it to json we call the BaseSerializer directly, because we want a Dictionary rather then a list
ret = super(serializers.ListSerializer, self).data
return ReturnDict(ret, serializer=self)
</code></pre>