我正在尝试将外键序列化为字典而不是数组。现在,json看起来如下所示:
{
"slug": "en",
"children": [{
"slug": "pants",
"children": [{
"slug": "products/:level1",
"children": [{
"slug": ":level2/:level3",
"children": []
}]
},
{
"slug": ":productSlug",
"children": []
}
]
},
{
"slug": "pullovers",
"children": []
}
]
}
但我希望它能使用这些弹头作为密钥:
{
"en": {
"children": {
"pants": {
"children": {
"products/:level1": {
"children": {
":level2/:level3": {
"children": {}
}
}
}
},
":productSlug": {
"children": {}
}
]
}
}
}
有没有可能直接在序列化程序中这样做,或者我必须在额外的步骤中转换它?
发布于 2017-07-21 20:51:51
可以通过覆盖list serializers并为每个需要它的序列化程序设置list_serializer_class
,正如我在此answer中建议的那样。
当然,你需要稍微调整一下:
class <YourClass>ListSerializer(serializers.ListSerializer):
def to_representation(self, data):
r = super().to_representation(data)
return { item['<key_field>']: item for item in r }
发布于 2017-07-25 17:34:36
@Michael Rigonis answer (https://stackoverflow.com/a/45238191/270265)是成功的关键。我必须对它进行一些调整,所以我也可以在顶层使用它。
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)
https://stackoverflow.com/questions/45235931
复制相似问题