Django - 如何链接表

时间:2015-04-25 08:31:42

标签: python mysql sql django

stackoverflow团队的问候,

我有以下两个django表:

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'

在views.py中,我知道我可以将以下内容完美地运行:

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

正如我上面提到的,这一切都运作良好,但我希望返回可以在StraightredTeam模型中找到的hometeamid的团队名称。

经过一些环顾四周后,我已经朝着“select_related”的方向轻推了一下,但我不清楚如何在现有的表中实现它,以及它是否是这类查询的最有效方式。感觉很好。

请注意,此代码是使用“python manage.py inspectdb”创建的。

在此阶段的任何建议将不胜感激。非常感谢,艾伦。

2 个答案:

答案 0 :(得分:1)

我不确定这对Managed=False是否有意义,但我想在Django中这样做的理智方式是

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

然后只使用fixture.home_team而不是手工查询。

答案 1 :(得分:1)

请参阅model relationships

Django提供特殊的模型字段来管理表关系。 符合您需求的是ForeignKey

而不是声明:

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

我猜是python manage.py inspectdb的结果,你会声明:

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')

通过这样做,您告诉Django ORM处理引擎盖下的关系,这将允许您执行以下操作:

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.