[英]Django ManyToMany with through model implementation
So let's say I have these models in my Django app: 因此,假设我的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
Now I want to access a recipe's ingredients (really RecipeIngredients). 现在,我要访问食谱的成分(确实是RecipeIngredients)。 Via the Django shell:
通过Django shell:
>>> r = Recipe.objects.get(id=1)
>>> ingredients = RecipeIngredients.objects.filter(recipe=r)
This seems counter-intuitive and clunky to me. 在我看来,这是违反直觉和笨拙的。 Ideally I'd like to be able to have a Recipe object and get RecipeIngredients from it directly.
理想情况下,我希望能够拥有一个Recipe对象并直接从中获取RecipeIngredients。
Is there a more elegant implementation of my models? 我的模型有更好的实现吗? Is there any way to improve my existing model implementation?
有什么方法可以改善我现有的模型实现?
Use related_name
, just as you would with a normal ForeignKey
or ManyToManyField
: 使用
related_name
,就像使用普通的ForeignKey
或ManyToManyField
:
class RecipeIngredients(models.Model):
recipe = models.ForeignKey(Recipe, related_name='ingredient_quantities')
And then: 接着:
>>> r = Recipe.objects.get(id=1)
>>> ingredients = r.ingredient_quantities.all()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.