Django REST框架:禁止直接分配到多对多集合的前端

时间:2018-06-06 09:58:58

标签: django django-rest-framework

我有食谱和成分类,我在成分模型上放置了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)

错误
TypeError:禁止直接分配到多对多集的前端。请改用ingredients.set()。

1 个答案:

答案 0 :(得分:1)

正如错误消息和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模型中。