我有一个用django rest框架构建的API。 这是代码:
models.py
class Ingredient(models.Model):
barcode = models.CharField(max_length=13, primary_key=True)
name = models.CharField(max_length=255)
image = models.CharField(max_length=255)
class Recipe(models.Model):
name = models.CharField(max_length=255)
favorite = models.BooleanField()
owner = models.ForeignKey(
'auth.User', related_name="recipes", on_delete=models.CASCADE)
class Component(models.Model):
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
recipe = models.ForeignKey( Recipe, related_name='components', on_delete=models.CASCADE)
quantity = models.FloatField()
serializers.py
class IngredientSerializer(serializers.ModelSerializer):
name = serializers.CharField(read_only=True)
image = serializers.CharField(read_only=True)
class Meta:
model = Ingredient
fields = '__all__'
class ComponentSerializer(serializers.ModelSerializer):
ingredient = serializers.PrimaryKeyRelatedField(queryset=Ingredient.objects.all())
# ingredient = IngredientSerializer()
class Meta:
model = Component
fields='__all__'
class RecipeSerializer(serializers.ModelSerializer):
components = ComponentSerializer(many=True)
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Recipe
fields = '__all__'
使用此状态的代码,我可以通过选择现有成分,现有配方和输入数量来创建新组件。但是,组件的序列化不是嵌套的:
{
"id": 8,
"quantity": 123.0,
"ingredient": "3218930313023"
},
当我在ComponentSerializer类中将代码更改为ingredient = IngredientSerializer()
时,表示按预期嵌套:
{
"id": 9,
"ingredient": {
"barcode": "3218930313023",
"name": "Crêpes L'Authentique",
"image": "https://static.openfoodfacts.org/images/products/321/893/031/3023/front_fr.16.400.jpg",
},
"quantity": 123.0
}
但是当我尝试添加具有现有配方和现有成分的组件时,我收到错误400,并显示以下消息:
{
"ingredient": {
"barcode": [
"ingredient with this barcode already exists."
]
}
}
在第一个代码中添加组件时,获得相同行为的最佳方法是什么,但是在第二个代码中使用嵌套表示?
非常感谢你的帮助。