[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)
πŸ‘€HaoQi Li

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