Reputation: 6296
I have a model that has a JSON field extra_data that contains other fields that might be added to the model. 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.
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
Upvotes: 0
Views: 495
Reputation: 881
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
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
Upvotes: 2