我正在制作几种烹饪模型,包括django,食谱和配料。 我使用多对多字段来关联它们。现在,我想为每个关系分配一个数字,所以从
开始 recipe.ingredients = [sugar,egg]
到
recipe.ingredients = {sugar:200,egg:2}
我该怎么做?明确构建第三个模型ingredients_recipes是100%必要的吗?该表应该已经存在,但我想知道是否可以直接使用多对多字段。
答案 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')