それでは、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 シェル経由:
>>> r = Recipe.objects.get(id=1)
>>> ingredients = RecipeIngredients.objects.filter(recipe=r)
これは私には直感に反し、不格好に思えます。理想的には、Recipe オブジェクトを持ち、そこから RecipeIngredients を直接取得できるようにしたいと考えています。
私のモデルのよりエレガントな実装はありますか? 既存のモデルの実装を改善する方法はありますか?