如何同时保存ForeignKey对象及其父对象



Angular 8,Django 3。我有两个型号RecipeIngredients。我在前端使用ngModels向Django发送数据以创建Recipe模型。在一个页面上,当您单击"提交"时,所有RecipeIngredients数据都会发送到后端。

从我读到的关于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

最新更新