gpt4 book ai didi

python - Django - 如何链接表格

转载 作者:行者123 更新时间:2023-11-29 06:27:51 25 4
gpt4 key购买 nike

你好,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”创建的。

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

最佳答案

参见 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.

关于python - Django - 如何链接表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29862881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com