问题
I have two models, Recipe
and Ingredient
. The Recipe model has a manytomany relationship with Ingredients, but I also need to be able to specify the quantity of the ingredients. My models currently look like:
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)
But obviously each recipe will have different quantities of each ingredient. So I need to be able to do something like:
cakeRecipe = Recipe.objects.get(pk=1)
flour = Ingredient.objects.get(pk=2)
cakeRecipe.ingredients.add(flour, '200 grams')
But I don't know how. Any help would be greatly appreciated. Thanks :)
回答1:
You need to follow the instructions on 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)
回答2:
You want an intermediatery model. As in - some model that will link between the two, using the 'through' argument. Like so:
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 ...
Read more about it here.
来源:https://stackoverflow.com/questions/19279480/django-many-to-many-relationship-with-another-field