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?
但是对于RecipeContent中的__unicode __(),我想使用这个RecipeContent所属的Recipe名称......有没有办法做到这一点?
4 个解决方案
#1
26
class RecipeContent(models.Model):
...
def __unicode__(self):
# You can access ForeignKey properties through the field name!
return self.recipe.name
#2
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)
#3
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.
是的,你可以(作为bishanty点),但是在调用__unicode __()但是尚未设置FK的情况下做好准备。我进入这几次。
#4
0
In Python 3 there is no __unicode__
, you need to use __str__
instead.
在Python 3中没有__unicode__,你需要使用__str__。
class RecipeContent(models.Model):
...
def __str__(self):
return self.recipe.name
#1
26
class RecipeContent(models.Model):
...
def __unicode__(self):
# You can access ForeignKey properties through the field name!
return self.recipe.name
#2
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)
#3
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.
是的,你可以(作为bishanty点),但是在调用__unicode __()但是尚未设置FK的情况下做好准备。我进入这几次。
#4
0
In Python 3 there is no __unicode__
, you need to use __str__
instead.
在Python 3中没有__unicode__,你需要使用__str__。
class RecipeContent(models.Model):
...
def __str__(self):
return self.recipe.name