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
You declare
geography
as a ForeignKey inCar
. 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:
and in your serializer: