0

在使用序列化程序创建对象时,我想为外键字段使用不同的名称。假设我有一个A带有外键字段b的模型来建模B。我该怎么做?

class A(models.Model):
    b = models.ForeignKey(B, related_name='a')

class AS(serializer.Serializer):
    b_id = ?? ## Some thing here so that b_id fills up the b field of A
    class Meta:
       fields = ('b_id')

我有不同的序列化程序用于创建和获取详细信息。在获取详细信息时,我使用嵌套序列化程序来获取详细信息,B这就是为什么我想b_id在仅指定 id 和b从中获取数据时使用字段B

编辑:

我试过了

b_id = serializers.PrimaryKeyRelatedField(source='b', queryset=B.objects.all())

但它给出了以下错误:

{
  "b_id": [
    "Incorrect type. Expected pk value, received int."
  ]
}
4

0 回答 0