EroSan
EroSan

Reputation: 339

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?

Upvotes: 12

Views: 5332

Answers (4)

jtrip
jtrip

Reputation: 1

In Python 3 there is no __unicode__, you need to use __str__ instead.

    class RecipeContent(models.Model):
        ...
        def __str__(self):
            return self.recipe.name

Upvotes: 0

HaoQi Li
HaoQi Li

Reputation: 12348

If you only care about the name part of the Recipe, you can do:

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

    def __unicode__(self):
        return self.name

class RecipeContent(models.Model):
    recipe = models.ForeignKey(Recipe)
    ...

    def __unicode__(self):
        return str(self.recipe)

Upvotes: 2

zgoda
zgoda

Reputation: 12895

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.

Upvotes: 0

jb.
jb.

Reputation: 10227

class RecipeContent(models.Model):
  ...
  def __unicode__(self):
    # You can access ForeignKey properties through the field name!
    return self.recipe.name

Upvotes: 26

Related Questions