我发现在创建所有未创建的对象之前,无法建立ManyToMany关系。(有关多对多关系,请参见Django Docs 页面。)
这是工作代码:
serializers.py
class RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True) class meta: model = Recipe def create(self, validated_data): ingredients_data = validated_data.pop('ingredients') recipe = Recipe.objects.create(**validated_data) for ingredient in ingredients_data: ingredient, created = Ingredient.objects.get_or_create(name=ingredient['name']) recipe.ingredients.add(ingredient) return recipe
以下是我的update()代码。但是,我已经好几年没有对此进行研究了,也不知道它是正确的还是良好的。我已经有一段时间没有在Python或Django上工作了,所以请一take而就:
def update(self, instance, validated_data): ingredients_data = validated_data.pop('ingredients') instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.directions = validated_data.get('directions', instance.directions) instance.photo = validated_data.get('photo', instance.photo) ingredients_list = [] for ingredient in ingredients_data: ingredient, created = Ingredient.objects.get_or_create(name=ingredient["name"]) ingredients_list.append(ingredient) instance.ingredients = ingredients_list instance.save() return instance
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)