我正在构建一个 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
