您好,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”创建的。
在此阶段的任何建议将不胜感激。非常感谢,艾伦。
请参阅模型关系。
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句