我在这里有一些关于添加到我的模型中的关系字段(herd/herd_id)
的问题。它不会作为Animal
模型和AnimalSerializer
djangorestframework
这是我的动物模型和序列化器:
models.py
class Animal(models.Model):
this_id = models.CharField(max_length=25)
name = models.CharField(max_length=25)
species_type = models.CharField(max_length=25)
breed = models.CharField(max_length=25)
date_of_birth = models.DateField()
birth_weight = models.IntegerField()
sex = models.CharField(max_length=7)
sibling_order = models.IntegerField()
sire_id = models.CharField(max_length=20)
sire_name = models.CharField(max_length=25)
dam_id = models.CharField(max_length=25)
dam_name = models.CharField(max_length=25)
rf_id = models.CharField(max_length=25)
comment = models.TextField(max_length=250, null=True)
herd = models.ForeignKey(Herd, related_name='animals', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
class Meta:
ordering = ('name',)
serializers.py
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = (
'this_id',
'name',
'species_type',
'breed',
'date_of_birth',
'birth_weight',
'sibling_order',
'sex',
'sire_id',
'sire_name',
'dam_id',
'dam_name',
'rf_id',
'comment',
'herd_id', // <--- this field wont appear in the djangorestframework UI.
'created_at',
'updated_at',
)
read_only_fields = ('id', 'created_at', 'updated_at')
这是图片。并查找它不会出现的herd_id
字段。请帮助
答案 0 :(得分:0)
我只需将herd_id
更改为herd
列名称,以便django识别匹配的序列化名称。