[英]Django ManyToMany with through model implementation
因此,假設我的Django應用程序中包含以下模型:
class Ingredient(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Recipe(models.Model):
name = models.CharField(max_length=100)
ingredients = models.ManyToManyField(Ingredient,
through='RecipeIngredient')
def __unicode__(self):
return self.name
class RecipeIngredient(models.Model):
recipe = models.ForeignKey(Recipe)
ingredient = models.ForeignKey(Ingredient)
quantity = models.DecimalField(max_digits=4, decimal_places=2)
unit = models.CharField(max_length=25, null=True, blank=True)
def __unicode__(self):
return self.ingredient.name
現在,我要訪問食譜的成分(確實是RecipeIngredients)。 通過Django shell:
>>> r = Recipe.objects.get(id=1)
>>> ingredients = RecipeIngredients.objects.filter(recipe=r)
在我看來,這是違反直覺和笨拙的。 理想情況下,我希望能夠擁有一個Recipe對象並直接從中獲取RecipeIngredients。
我的模型有更好的實現嗎? 有什么方法可以改善我現有的模型實現?
使用related_name
,就像使用普通的ForeignKey
或ManyToManyField
:
class RecipeIngredients(models.Model):
recipe = models.ForeignKey(Recipe, related_name='ingredient_quantities')
接着:
>>> r = Recipe.objects.get(id=1)
>>> ingredients = r.ingredient_quantities.all()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.