4

我有两个模型,RecipeIngredient。Recipe 模型与成分有多对多关系,但我还需要能够指定成分的数量。我的模型目前看起来像:

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')

但我不知道怎么做。任何帮助将不胜感激。谢谢 :)

4

2 回答 2

3

您需要遵循关于多对多关系的额外字段的说明:

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)
于 2013-10-09T18:13:45.963 回答
2

你想要一个中间模型。如 - 使用“通过”参数将两者联系起来的一些模型。像这样:

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 ...

在此处阅读更多相关信息。

于 2013-10-09T18:13:39.123 回答