Django Many to Many Relationship With Another Field

流过昼夜 提交于 2020-01-15 03:30:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!