Django select_related query
<p>I have the following two models:</p>

<pre><code>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'
</code></pre>

<p>I am using the following query:</p>

<pre><code>    prevWeekTeams = UserSelection.objects.select_related().filter(soccerseason=1025,fixturematchday=5,user=currentUserID).order_by('teamselection1or2')
</code></pre>

<p>When it is run I get the following error:</p>

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

<p>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.</p>

<p>PS</p>

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

<p>You just need to filter on field of foreign model with that format </p>

<p><code>field-that-reference-to-foreign-model__foreign-model-field</code> in your case <code>fixtureid__soccerseason</code>. <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">The docs</a> where it describes at best.</p>

<p>What you should do is</p>

<pre><code>prevWeekTeams = UserSelection.objects.filter(fixtureid__soccerseason=1025,fixtureid__fixturematchday=5,user=currentUserID).order_by('teamselection1or2')
</code></pre>

python mysql django