[Answered ]-Django โ€“ How to link tables

1๐Ÿ‘

โœ…

See model relationships.

Django provides special model fields to manage table relationships.
The one suiting your needs is ForeignKey.

Instead of declaring:

hometeamid = models.IntegerField()
awayteamid = models.IntegerField()

which I guess is the result of python manage.py inspectdb, you would 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 this will, you tell the Django ORM to handle the relationship under the hood, which will allow you to do such things as:

fixture = StraightredFixture.objects.get(fixtureid=some_fixture_id)
fixture.home_team  # Returns the associated StraightredTeam instance.

team = StraightredTeam.objects.get(team_id=some_team_id)
team.home_fixtures.all()  # Return all at home fixtures for that team.
๐Ÿ‘คaumo

1๐Ÿ‘

I am not sure if this makes sense for Managed=False, but I suppose the sane way of doing it in Django would be with

home_team = models.ForeignKey('StraightRedFixture', db_column='fixtureid'))

And then just using fixture.home_team instead of doing queries by hand.

๐Ÿ‘คTobia Tesan

Leave a comment