python - Django - How to link tables -
hello stackoverflow team,
i have following 2 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 views.py know can put following , works perfectly:
def test(request): fixture = straightredfixture.objects.get(fixtureid=136697) return render(request,'straightred/test.html',{'name':fixture.hometeamid})
as mentioned above, works looking return teamname of hometeamid can found in straightredteam model.
after looking around have been nudged in direction of "select_related" unclear on how implement in existing tables , if efficient way type of query. feels right.
please note code created using "python manage.py inspectdb".
any advice @ stage appreciated. many thanks, alan.
see model relationships.
django provides special model fields manage table relationships. 1 suiting needs foreignkey.
instead of declaring:
hometeamid = models.integerfield() awayteamid = models.integerfield()
which guess result of python manage.py inspectdb
, declare:
home_team = models.foreignkey('<app_name>. straightredteam', db_column='hometeamid', related_name='home_fixtures') away_team = models.foreignkey('<app_name>. straightredteam', db_column='awayteamid', related_name='away_fixtures')
by doing will, tell django orm handle relationship under hood, allow such things as:
fixture = straightredfixture.objects.get(fixtureid=some_fixture_id) fixture.home_team # returns associated straightredteam instance. team = straightredteam.objects.get(team_id=some_team_id) team.home_fixtures.all() # return @ home fixtures team.
Comments
Post a Comment