gpt4 book ai didi

Django REST 框架 : direct assignment to the forward side of a many-to-many set is prohibited

转载 作者:行者123 更新时间:2023-12-01 23:37:45 25 4
gpt4 key购买 nike

我有一个配方和成分类,我在成分模型上放置了一个 m2m。我在管理面板中测试了模型并且工作正常。但是,当我尝试在 shell 中创建它们时,出现错误(请参阅下面的错误)。

class Ingredient(models.Model):
name = models.CharField(max_length=50)
amount = models.IntegerField(default=1)
ingredients = models.ManyToManyField(Recipe, related_name='ingredients')


class IngredientSerializer(ModelSerializer):
class Meta:
fields = ['name', 'amount']
model = Ingredient



class Recipe(models.Model):
owner = models.ForeignKey('auth.User', related_name='recipes', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
description = models.TextField(max_length=200, blank=True)
image = models.CharField(max_length=100, blank=True)


class RecipeSerializer(ModelSerializer):
ingredients = IngredientSerializer(many=True)
owner = ReadOnlyField(source='owner.username')

class Meta:
fields = ['owner', 'name', 'description', 'image', 'ingredients']
model = Recipe

Shell 命令
beefsoup = Recipe.objects.create(owner=user, name="beef", description="goot", image="httplo")
tomatoes = Ingredient.objects.create(ingredients=beefsoup ,name='tomatoes', amount=2)

错误
类型错误:禁止直接分配给多对多集合的前端。改用成分.set()。

最佳答案

作为错误信息和 Django Docs建议,您的代码段应如下所示:

  beefsoup = Recipe.objects.create(owner=user, name="beef", description="goot", image="httplo")
beefsoup.ingredients.create(name='tomatoes', amount=2)

除此之外,从模型和属性名称来看,您的关系设计似乎不正确。它应该看起来像这样:
class Ingredient(models.Model):
name = models.CharField(max_length=50)
amount = models.IntegerField(default=1)


class IngredientSerializer(ModelSerializer):
class Meta:
fields = ['name', 'amount']
model = Ingredient


class Recipe(models.Model):
owner = models.ForeignKey('auth.User', related_name='recipes', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
description = models.TextField(max_length=200, blank=True)
image = models.CharField(max_length=100, blank=True)
ingredients = models.ManyToManyField(Ingredients, related_name='recipes')


class RecipeSerializer(ModelSerializer):
ingredients = IngredientSerializer(many=True)
owner = ReadOnlyField(source='owner.username')

class Meta:
fields = ['owner', 'name', 'description', 'image', 'ingredients']
model = Recipe

请注意 ingredients现居 Recipe模型。

关于Django REST 框架 : direct assignment to the forward side of a many-to-many set is prohibited,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50717539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com