samedi 25 avril 2015

Django - How to link tables


Hello to the stackoverflow team,

I have the following two django tables:

class StraightredFixture(models.Model):
    fixtureid = models.IntegerField(primary_key=True)
    soccerseason = models.IntegerField(db_column='soccerSeason')  # Field name made lowercase.
    hometeamid = models.IntegerField()
    awayteamid = models.IntegerField()
    fixturedate = models.DateTimeField()
    fixturestatus = models.CharField(max_length=24)
    fixturematchday = models.IntegerField()
    hometeamscore = models.IntegerField()
    awayteamscore = models.IntegerField()

    class Meta:
        managed = False
        db_table = 'straightred_fixture'

class StraightredTeam(models.Model):
    teamid = models.IntegerField(primary_key=True)
    teamname = models.CharField(max_length=36)
    teamcode = models.CharField(max_length=5)
    teamshortname = models.CharField(max_length=24)

    class Meta:
        managed = False
        db_table = 'straightred_team'

In the views.py I know I can put the following and it works perfectly:

def test(request):
    fixture = StraightredFixture.objects.get(fixtureid=136697)
    return render(request,'straightred/test.html',{'name':fixture.hometeamid})

As I mentioned above, this all works well but I am looking to return the teamname of the hometeamid which can be found in the StraightredTeam model.

After some looking around I have been nudged in the direction of "select_related" but I am unclear on how to implement it in my existing tables and also if it is the most efficient way for this type of query. It feels right.

Any advice at this stage would be greatly appreciated. Many thanks, Alan.


Aucun commentaire:

Enregistrer un commentaire