views:

323

answers:

2

I have the following classes: Ingredients, Recipe and RecipeContent...

class Ingredient(models.Model):
    name = models.CharField(max_length=30, primary_key=True)
    qty_on_stock = models.IntegerField()

    def __unicode__(self):
        return self.name

class Recipe(models.Model):
    name = models.CharField(max_length=30, primary_key=True)
    comments = models.TextField(blank=True)
    ingredient = models.ManyToManyField(Ingredient)

    def __unicode__(self):
        return self.name

class RecipeContent(models.Model):
    recipe = models.ForeignKey(Recipe)
    ingredients = models.ForeignKey(Ingredient)
    qty_used = models.IntegerField()

but for __unicode__() in RecipeContent I would like to use the Recipe name to which this RecipeContent belongs to... is there a way to do it?

+8  A: 
class RecipeContent(models.Model):
  ...
  def __unicode__(self):
    # You can access ForeignKey properties through the field name!
    return self.recipe.name
jb
sigh... it was so simple! shows what a noob I am...Thanks for the answer.
EroSan
A: 

Yes, you can (as bishanty points), but be prepared for situation when __unicode__() is called but FK is not set yet. I came into this few times.

zgoda
true... but maybe i can deal with that using something along the lines of "if self.recipe.name: return self.recipe.name"?
EroSan