所以我想说我在我的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。
我的模型有更优雅的实现吗?有没有办法改善我现有的模型实施?
答案 0 :(得分:1)
使用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()