Reputation: 3125
So let's say I have these models in my Django app:
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). Via the 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.
Is there a more elegant implementation of my models? Is there any way to improve my existing model implementation?
Upvotes: 0
Views: 336
Reputation: 53669
Use related_name
, just as you would with a normal ForeignKey
or 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()
Upvotes: 1