Like mentioned in the title.I have such JSON array being returned from backend:
[
{id:1, name:'name1'},
{id:2, name:'name2'},
{id:3, name:'name3'},
{id:4, name:'name4'}
]
and I would like to return something like this instead:
{
"1": {id:1, name:'name1'},
"2": {id:2, name:'name2'},
"3": {id:3, name:'name3'},
"4": {id:4, name:'name4')
}
Is it possible in Django Rest framework to send such object as Response ? Obviously there will not be too many keys so size should not be an issue.
You can modify the data before sending it to the client.
data = [
{id:1, name:'name1'},
{id:2, name:'name2'},
{id:3, name:'name3'},
{id:4, name:'name4'}
]
data = {key["id"]:value for value in data}
return JsonResponse(data)
Alternative If you are using serializer
If you are using serializer use to_representation to modify data while serializing it. It will have no performance impact on than the default representation.
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModal
fields = ('foo', 'bar', .....,)
def to_representation(self, instance):
row = super(MySerializer, self).to_representation(instance)
return {row["id"]:row}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With