0

序列化程序.py

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

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

模型.py

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

我想要的对象:

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

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

我得到的对象:

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

}
]

我正在使用的数据具有 car_id 和 key 属性的重复值。我还有另一个困惑是应该是外键还是多对多字段。任何帮助,将不胜感激

4

1 回答 1

0

您在 中声明geography为 ForeignKey Car。在自然语言中,这翻译为One car属于Geography,而在您的问题描述中,它更像是One car has many to Geography,这与 M2M 关系有关。

所以......在你的模型中它应该变成:

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

并在您的序列化程序中:

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

    class Meta:
        model = Car
        fields = ['car_id', 'geographies']
于 2019-10-27T12:54:16.787 回答