DRF ManyToMany instances add not create



我的模型有以下代码:

class Recipe(BaseModel):
"""
Recipe model class using for contains recipe, which can be sent to chat
with coach. In text recipe contains RecipeStep.
"""
ingredients = models.ManyToManyField(
Product,
verbose_name=_("ingredients"),
related_name="ingredients"
)
portion_size = models.PositiveSmallIntegerField(
_("portion size")
)
# TODO: add "add_to_meal" logic (user can add recipe to his meal).
# it can be reached by using M2M with user and creating new relation for 
# user and recipe on user click on special button.
def __str__(self) -> str:
return f"recipe "{self.title}""

def __repr__(self) -> str:
return f"Recipe({self.pk=}, {self.title=}, {self.is_published=})"

class Meta:
verbose_name = _("recipe")
verbose_name_plural = _("recipes")

BaseModel是抽象类,具有类文章模型的基本结构(title、description、publishhed_at等)。

和以下模型序列化器的代码:

class RecipeSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(read_only=True)
title = serializers.CharField(min_length=1, max_length=200, required=True)
ingredients = ProductSerializer(many=True, read_only=False)
portion_size = serializers.IntegerField(min_value=0, required=True)
is_published = serializers.BooleanField(required=False, default=False)
publish_date = serializers.DateField(
allow_null=True,
required=False,
read_only=True
)
image_add_id = serializers.UUIDField(required=True)

def create(self, validated_data):
validated_data.pop('image_add_id', None)
return super().create(validated_data)
class Meta:
model = Recipe
fields = "__all__"

我需要创建配方与传递现有成分的列表,而不是创建新的成分,如:

{
...
"ingredients": [
"d6c065a2-7f80-47f3-8c0e-186957b07269",
"4b8359d2-073a-4f41-b3cc-d8d2cfb252d5",
"b39e4cc2-18c3-4e4a-880a-6cb2ed556160",
"603e2333-0ddf-41f1-99f5-3dfe909eb969"
]
}

我该怎么做?

您正在使用模型序列化器,因此您不必重新定义序列化器字段。也因为你是添加许多相关领域后你必须添加模型实例创建遵循

class RecipeSerializer(serializers.ModelSerializer):
class Meta:
model = Recipe
fields = '__all__'

def create(self, validated_data):
ingredients = validated_data.pop('ingredients')
instance = super().create(validated_data)
for ingredient in ingredients:
instance.ingredients.add(ingredient)
return instance

相关内容

最新更新