Django:Python访问onetone字段

时间:2016-10-29 21:32:17

标签: python django

我有以下代码:

fixtures = StraightredFixture.objects.select_related().filter(soccerseason=soccerseason,fixturematchday=fixturematchday).order_by('fixturedate')
temp2 = fixtures[0].hometeamscore

它有效,但它正在使用模型“StraightredFixture”中的“hometeamscore”,但我需要它来自“StraightredFixtureLive”。有人可以帮我修改我的代码吗,非常感谢,Alan。

这两个模型如下:

class StraightredFixture(models.Model):
    fixtureid = models.IntegerField(primary_key=True)
    home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures')
    away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures')
    fixturedate = models.DateTimeField(null=True)
    fixturestatus = models.CharField(max_length=24,null=True)
    fixturematchday = models.ForeignKey('straightred.StraightredFixtureMatchday', db_column='fixturematchday')
    spectators = models.IntegerField(null=True)
    hometeamscore = models.IntegerField(null=True)
    awayteamscore = models.IntegerField(null=True)   

    def __unicode__(self):
        return self.fixtureid

    class Meta:
        managed = True
        db_table = 'straightred_fixture'

class StraightredFixtureLive(models.Model):
    fixtureid = models.OneToOneField(StraightredFixture, on_delete=models.CASCADE, primary_key=True,)
    hometeamscore = models.IntegerField(null=True)
    awayteamscore = models.IntegerField(null=True)

    def __unicode__(self):
        return self.fixtureid

    class Meta:
        managed = True
        db_table = 'straightred_fixturelive'

1 个答案:

答案 0 :(得分:1)

只需访问相关的一对一字段实例,然后访问实例的hometeamscore字段:

temp = fixtures[0].straightredfixturelive.hometeamscore
#                  ^^^^^^^^^^^^^^^^^^^^^^