[英]Serialize complex fields in django rest framework
I have a model that has a JSON field extra_data that contains other fields that might be added to the model. 我有一个具有JSON字段extra_data的模型,该字段包含可能添加到模型中的其他字段。 From the beginning it is not known how many fields will be added apart from the compulsory ones, which is why I introduced the extra_data field. 从一开始就不知道除了强制字段外还会添加多少个字段,这就是为什么我引入了extra_data字段的原因。
With the usual rest framework serialization I currently have something like this: 通过通常的其余框架序列化,我目前有以下内容:
[
{
"code": "1",
"name": "Moscow",
"extra_data": {
"type": "Region"
}
},
{
"code": "2",
"name": "Tatarstan",
"extra_data": {
"type": "Republic",
"capital": "Kazan"
}
}
]
But what I need something is like this: 但是我需要的是这样的:
[
{
"code": "1",
"name": "Moscow",
"type": "City"
},
{
"code": "2",
"name": "Tatarstan",
"type": "Republic",
"capital": "Kazan"
}
]
Please I need help, I'm new to django 请我需要帮助,我是django的新手
The serializer itself I don't think can do this, since you do not know how many fields are there. 我不认为串行器本身可以做到这一点,因为您不知道有多少个字段。 But once you get the serializer.data, you may update your dict like: 但是一旦获得serializer.data,就可以像下面这样更新字典:
serializer_data = serializer.data
extra_data = serializer_data.pop('extra_data')
serializer_data.update(extra_data)
return serializer_data
I'm no expert on Django so I'm not telling you for sure that there is no way of doing that withing the serializer, but none that I can think of 我不是Django的专家,所以我无法肯定地告诉您,使用序列化程序无法做到这一点,但是我想不到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.