How to serialize a foreign key relationship as key value pair django rest framework

Viewed 30

I'm trying to serialize an relationship in DRF whereas I attempt to get the following output:

"statistics":[
   "Attacks":{
      "id":971,
      "home_value":3,
      "away_value":2,
      "value":5
   },
   "Corners":{
      "id":972,
      "home_value":0,
      "away_value":0,
      "value":0
   }
]

I wrote the following code for my serializer of this model:

class StatisticSerializer(serializers.ModelSerializer):
    class Meta: 
        model = Statistic
        fields = ['id', 'home_value', 'away_value', 'name', 'value']

    def to_representation(self, instance: Statistic):
        representation = {instance.name: {
            "id": instance.id, 
            "home_value": instance.home_value,
            "away_value": instance.away_value, 
            "value": instance.value
        }}

        return representation

Which gets me the following output:

"statistics":[
   {
      "Attacks":{
         "id":971,
         "home_value":3,
         "away_value":2,
         "value":5
      }
   },
   {
      "Corners":{
         "id":972,
         "home_value":0,
         "away_value":0,
         "value":0
      }
   }
]

Is there any way to get it as demonstrated in the first example using django rest framework?

0 Answers
Related