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
Source:stackexchange.com