【发布时间】:2014-03-15 20:39:26
【问题描述】:
我想在 Django admin 中显示一个对象有多少个关系。
假设我有以下模型:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
我想在投票问题旁边的管理员 (list_display) 中显示可供选择的数量。有没有办法向 Question 类添加一个函数,该函数将返回它有多少个选择?
编辑
这是一个假设模型。我正在使用带有文件存储的模型,并想计算有多少文件连接到“主”模型,或者在本例中为 Question 类。
【问题讨论】:
-
你可以试试
count = Question.choice_set.count()吗? -
@anishshah 我添加的代码是一个假设模型,在我的情况下,
Choice类实际上是一个文件存储模型,我想计算有多少文件链接到“问题”模型。所以choice_set 在这里不起作用。
标签: python django foreign-keys admin database-relations