Django Rest Framework: nested serializer for duplicate rows, in the case of foreign key

910 Views Asked by At

serializer.py

class Car(serializers.ModelSerializer):
    geography=Geography(read_only=True)

    class Meta:
        model = Car
        fields = ['car_id', 'geography']

models.py

 class Car(models.Model):
      car_id = models.IntegerField(null=False)
      geography = models.ForeignKey('Geography' ,on_delete=models.CASCADE)

the object that I want :

 [
{
    "car_id": 1,
    "geography":[ {
        "key": 1,
        "name": "India"},

    {"key": 1,
          "name": "China"
}
   ]        
 } 
]

the object that I am getting:

[
{
    "car_id": 1,
    "geography": {
        "key": 1,
        "name": "India"}

}
]

The data that I am working with has duplicate values for car_id and key attributes. I have another confusion whether it should be foreign key or many to many field. Any help would be appreciated

1

There are 1 best solutions below

1
On

You declare geography as a ForeignKey in Car. In natural language, this translates to One car belongs to Geography, while in your problem description, it's more like One car has many to Geography, which related so M2M relation ship.

So... in your models it should become:

class Car(models.Model):
      car_id = models.IntegerField(null=False)
      geographies = models.ManyToManyField('Geography' ,on_delete=models.CASCADE)
      # take care: I changed field's name

and in your serializer:

class Car(serializers.ModelSerializer):
    geographies=Geography(read_only=True, many=True)

    class Meta:
        model = Car
        fields = ['car_id', 'geographies']