Alan Tingey Alan Tingey - 1 month ago 7
Python Question

Django: Python access to onetone field

I have the following code:

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


It works but it is using the "hometeamscore" from the model "StraightredFixture" but I need it from "StraightredFixtureLive". Could someone help me amend my code accordingly, many thanks, Alan.

The two models are as below:

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'

Answer

Just access the related One-to-One field instance and then the instance's hometeamscore field:

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