[Fixed]-Can I use a ForeignKey in __unicode__ return?

26👍

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

2👍

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)

0👍

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

0👍

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

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

Leave a comment