Django与另一个领域的许多关系 [英] Django Many to Many Relationship With Another Field

查看:112
本文介绍了Django与另一个领域的许多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种型号,配方成分。食谱模型与Ingredients具有多重关系,但我也需要能够指定成分的数量。我的模型目前看起来像:

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

推荐答案

您需要按照多对多关系的额外字段

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)

这篇关于Django与另一个领域的许多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆