Django与另一个字段的多对多关系
问题描述:
我有两个模型,Recipe
和Ingredient
。食谱模型与成分有许多关系,但我也需要能够指定成分的数量。我的模型目前看起来像:Django与另一个字段的多对多关系
class Ingredient(models.Model):
name = models.CharField(max_length="256", db_index=True, null=True)
class Recipe(models.Model):
...
ingredients = models.ManyToManyField(Ingredient, related_name="RecipeIngredients", db_index=True)
但显然每个配方将有不同数量的每种成分。所以我需要能够做到这样的事情:
cakeRecipe = Recipe.objects.get(pk=1)
flour = Ingredient.objects.get(pk=2)
cakeRecipe.ingredients.add(flour, '200 grams')
但我不知道如何。任何帮助将不胜感激。谢谢:)
答
你想要一个中间模型。如同 - 在一些模型中,将使用'through'参数来链接两者。像这样:
class Ingredient(models.Model):
name = models.CharField(max_length="256", db_index=True, null=True)
class Recipe(models.Model):
...
ingredients = models.ManyToManyField(Ingredient,
related_name="RecipeIngredients",
db_index=True,
through='Quantity')
class Quantity(models.Model):
ingrediant = models.ForeignKey(Ingredient)
recipe = models.ForeignKey(Recipe)
amount = models.IntegerField()
#... any other fields ...
了解更多关于它here。
答
您需要按照上Extra fields on many-to-many relationships说明:
class RecipeIngredient(models.Model):
recipe = models.ForeignKey('Recipe')
ingredient = models.ForeignKey('Ingredient')
quantity = models.CharField(max_length=200)
class Recipe(models.Model):
ingredients = models.ManyToManyField(Ingredient, through=RecipeIngredient)
+0
评论中的链接返回404。它应该是https://docs.djangoproject.com/en/1.10/topics/db/models/#extra-fields-on-many-to-many-relationships – Hexatonic
完美。我会试试看,非常感谢! – amba88