Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return key/attribute JSON object instead of array of JSONs for model Django Rest Framework

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.

like image 450
kenshin Avatar asked Dec 18 '25 10:12

kenshin


1 Answers

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}
        
like image 127
Suryaveer Singh Avatar answered Dec 20 '25 22:12

Suryaveer Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!