Angular 8,Django 3。我有两个型号Recipe
和Ingredients
。我在前端使用ngModels
向Django发送数据以创建Recipe
模型。在一个页面上,当您单击"提交"时,所有Recipe
和Ingredients
数据都会发送到后端。
从我读到的关于ManyToOne
关系的内容来看,models.ForeignKey
应该是"多"的一部分。所以每个Recipe
有"很多"Ingredients
,所以我在Ingredients
上有Foreignkey
。
我的问题是,当我将所有这些数据发送到Django时,我的Ingredients
没有被创建,因为RecipeSerializer
上没有ingredients
字段。
型号.py
class Recipe(models.Model):
name = models.CharField(max_length=30)
class Ingredients(models.Model):
name = models.CharField(max_length=50)
recipe = models.ForeignKey(Recipe, related_name='ingredients', on_delete=models.CASCADE)
视图.py
class AddRecipe(generics.CreateAPIView):
serializer_class = RecipeFullSerializer
序列化程序.py
class IngredientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingredients
fields = ['name']
class RecipeFullSerializer(serializers.ModelSerializer):
ingredients = IngredientSerializer(many=True, read_only=True)
class Meta:
model = Recipe
fields = ['name', 'ingredients']
样本数据
ingredients: Array(1)
0: {name: "23"}
length: 1
__proto__: Array(0)
name: "23"
我在后端得到了一个Ingredients
数据数组,只是不知道如何同时使用指向Recipes
的Foreignkey来保存所有数据。我想我可以创建一个自定义视图来为我做这一切,但我认为会有一个基于类的视图可以做到这一点。
错误
AssertionError: The `.create()` method does not support writable nested fields by default.
Write an explicit `.create()` method for serializer `users.serializers.RecipeFullSerializer`, or set `read_only=True` on nested serializer fields.
您将配料设置为read_only,因此它不会创建它们。如果你想保存它们,你需要删除它。
更新:此外,您还需要覆盖create方法。检查文档中嵌套表示的Writing.create((方法。
它应该是这样的:
class RecipeFullSerializer(serializers.ModelSerializer):
ingredients = IngredientSerializer(many=True)
class Meta:
model = Recipe
fields = ['name', 'ingredients']
def create(self, validated_data):
ingredients = validated_data.pop('ingredients')
recipe = Recipe.objects.create(**validated_data)
for ingredient in ingredients:
Ingredient.objects.create(recipe=recipe, **ingredient)
return recipe