Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a ForeignKey in __unicode__ return?

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?

like image 406
EroSan Avatar asked Dec 27 '08 19:12

EroSan


1 Answers

class RecipeContent(models.Model):
  ...
  def __unicode__(self):
    # You can access ForeignKey properties through the field name!
    return self.recipe.name
like image 190
jb. Avatar answered Oct 16 '22 17:10

jb.