gpt4 book ai didi

python - Django OneToOneField unicode 方法

转载 作者:太空宇宙 更新时间:2023-11-04 03:49:57 25 4
gpt4 key购买 nike

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

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