<p>我发现在所有未创建的对象都被创建之前,无法建立多个关系。(见Django文档<a href="https://docs.djangoproject.com/en/1.7/topics/db/examples/many_to_many/#many-to-many-relationships" rel="noreferrer">page on many-to-many relationships</a>。)</p>
<p>这是工作代码:</p>
<p><strong>序列化程序.py</strong></p>
<pre><code>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
</code></pre>
<h2>更新:</h2>
<p>根据@steppiercy的请求,下面是我的<code>update()</code>代码。<strong>然而</strong>,我已经好几年没看过这个了,也不知道它是正确的还是好的。我已经有一段时间没有在Python或Django中工作了,所以带上这个吧:</p>
<pre><code>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
</code></pre>