我正在构建一个 Django 应用程序来模拟足球比赛。我的两个模型是:
class Match(models.Model):
arsenal = models.OneToOneField('Roster', related_name="arsenalRoster")
opponent = models.OneToOneField('Roster', related_name="opponentRoster")
date = models.DateTimeField()
location = models.CharField(max_length=64)
...
class Roster(models.Model):
squad = models.ForeignKey('Squad')
def __unicode__(self):
if self.squad.season.footballClub.name is "Arsenal Football Club":
return u'%s, @%s' % (self.match.date, self.match.location)
else:
return u'%s, %s' % (self.match.date, self.squad.season.footballClub.name)
现在显然我无法返回 self.match.date,因为没有实例属性来访问匹配对象,并且相应地我收到错误: AttributeError: 'Roster' object has no attribute 'match'
.然而,这是我想根据给定条件返回的信息。是否可以从 Roster 对象访问 Match 对象的实例数据?如何在不更改模型的情况下实现我想要做的事情?
最佳答案
使用 related_name 而不是 match
:
#self.match.date
self.arsenalRoster.date
或者(您在Match
模型中有2个指向Roster
的链接):
self.opponentRoster.date
关于python - Django OneToOneField unicode 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21785493/