gpt4 book ai didi

python - 我可以在 __unicode__ 返回中使用 ForeignKey 吗?

转载 作者:太空狗 更新时间:2023-10-29 17:39:15 25 4
gpt4 key购买 nike

我有以下类(class):Ingredients、Recipe 和 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()

但是对于 RecipeContent 中的 __unicode__() 我想使用 RecipeContent 所属的 Recipe 名称...有没有办法做到这一点?

最佳答案

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

关于python - 我可以在 __unicode__ 返回中使用 ForeignKey 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/395340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com