Alan Tingey Alan Tingey - 2 months ago 8
MySQL Question

Django select_related query

I have the following two models:

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)
fixturematchday = models.ForeignKey('straightred.StraightredFixtureMatchday', db_column='fixturematchday')
hometeamscore = models.IntegerField(null=True)
awayteamscore = models.IntegerField(null=True)
soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_season')


def __unicode__(self):
return self.fixtureid

class Meta:
managed = True
db_table = 'straightred_fixture'

class UserSelection(models.Model):
userselectionid = models.AutoField(primary_key=True)
campaignno = models.CharField(max_length=36,unique=False)
user = models.ForeignKey(User, related_name='selectionUser')
teamselection1or2 = models.PositiveSmallIntegerField()
teamselectionid = models.ForeignKey('straightred.StraightredTeam', db_column='teamselectionid', related_name='teamID')
fixtureid = models.ForeignKey('straightred.StraightredFixture', db_column='fixtureid')


class Meta:
managed = True
db_table = 'straightred_userselection'


I am using the following query:

prevWeekTeams = UserSelection.objects.select_related().filter(soccerseason=1025,fixturematchday=5,user=currentUserID).order_by('teamselection1or2')


When it is run I get the following error:

Cannot resolve keyword 'soccerseason' into field. Choices are: campaignno, fixtureid, fixtureid_id, teamselection1or2, teamselectionid, teamselectionid_id, user, user_id, userselectionid


I knew it would not work but I can't quite understand how to refer to the soccerseason within the fixture table. Any help would be appreciated. Many thanks, Alan.

PS

If you require the other two models that are linked to just let me know.

Answer

You just need to filter on field of foreign model with that format

field-that-reference-to-foreign-model__foreign-model-field in your case fixtureid__soccerseason. The docs where it describes at best.

What you should do is

prevWeekTeams = UserSelection.objects.filter(fixtureid__soccerseason=1025,fixtureid__fixturematchday=5,user=currentUserID).order_by('teamselection1or2')
Comments