Model.py:
class Match(models.Model):
home_team = models.CharField(max_length=200)
away_team = models.CharField(max_length=200)
class Stat(models.Model):
match = models.ForeignKey(Match)
team = models.CharField(max_length=100)
goals = models.IntegerField(default=0)
assists = models.IntegerField(default=0)
views.py
context_dict = {}
match = Match.objects.get(pk=1)
home_stat = Stat.objects.get(match=match, team=match.home_team)
away_stat = Stat.objects.get(match=match, team=match.away_team)
context_dict['home_stat'] = home_stat
context_dict['away_stat'] = away_stat
return render(request, 'index.html', context_dict)
模板
goals: {{ home_stat.goals }} : {{ away_stat.goals }}
assists: {{ home_stat.assists }} : {{ away_stat.assists }}
django-debug-toolbar显示两个重复的查询: https://sfault-image.b0.upaiyun.com/220/984/2209840587-5a3e5ccccec87_articlex
SELECT "myapp_stat"."id", "myapp_stat"."match_id", "myapp_stat"."team", "myapp_stat"."goals", "myapp_stat"."assists" FROM "myapp_stat" WHERE ("myapp_stat"."match_id" = '1' AND "myapp_stat"."team" = '''TeamA''')
Duplicated 2 times.
F:\myproject\myapp/views.py in index(11)
home_stat = Stat.objects.get(match=match, team=match.home_team)
SELECT "myapp_stat"."id", "myapp_stat"."match_id", "myapp_stat"."team", "myapp_stat"."goals", "myapp_stat"."assists" FROM "myapp_stat" WHERE ("myapp_stat"."match_id" = '1' AND "myapp_stat"."team" = '''TeamB''')
Duplicated 2 times.
F:\myproject\myapp/views.py in index(12)
away_stat = Stat.objects.get(match=match, team=match.away_team)
如何解决这个问题?
答案 0 :(得分:0)
执行ORM查询时,您可以使用双下划线查找相关模型上的字段。 试试这个:
home_stat = Stat.objects.get(match=match)
away_stat = Stat.objects.get(match=match)
答案 1 :(得分:0)
正如您在ForeignKey
到Stat
中Match
一样,您可以使用Django默认提供的相关名称stat_set来简化查询。
match.stat_set.filter(...)
您可以按team__in
查找过滤统计信息。这意味着您需要一个SQL查询来获取这两个统计信息。
both_stats = match.stat_set.filter(team__in=[match.home_team, match.away_team])
剩下的就是将它们作为单独的对象。
for stat in both_stats:
if stat.team == match.home_team:
context_dict['home_stat'] = stat
elif stat.team == match.away_team:
context_dict['away_stat'] = stat
总的来说,这会将sql查询的数量从2减少到1但会增加python工作。