将属性分配给多对多关系

时间:2013-12-27 20:06:17

标签: django django-models

我正在制作几种烹饪模型,包括django,食谱和配料。 我使用多对多字段来关联它们。现在,我想为每个关系分配一个数字,所以从

开始

recipe.ingredients = [sugar,egg]

recipe.ingredients = {sugar:200,egg:2}

我该怎么做?明确构建第三个模型ingredients_recipes是100%必要的吗?该表应该已经存在,但我想知道是否可以直接使用多对多字段。

1 个答案:

答案 0 :(得分:4)

是的,您需要使用其他字段创建中间模型。然后,您可以在a through argument to the ManyToManyField中指定中间值,例如:

class Recipe(models.Model):
    #...
    ingredients = models.ManyToManyField(Ingredients, through="RecipeIngredients")

class RecipeIngredients(models.Model):
    recipe = models.ForeignKey(Recipe)
    ingredient = models.ForeignKey(Ingredient)
    amount = models.IntegerField()

    class Meta:
        unique_together = ('recipe', 'ingredient')

另请参阅官方文档:Extra fields on many-to-many relationships

相关问题