Django ORM select_related 渲染模板

Django ORM select_related rendering template

我在 Django 1.10 版本中有这个模型

class Game(models.Model):
    game_code = models.CharField(max_length=10)
    home_team = models.ForeignKey(Team, related_name="home_set", default=2, blank=True, null=True)
    away_team = models.ForeignKey(Team, related_name="away_set", default=2, blank=True, null=True)


class GameCoefficient(models.Model):
    game = models.ForeignKey(Game, default=3)
    win_type = models.CharField(choices=win_type, max_length=250,  blank=True, null=True, default="")
    value = models.FloatField(max_length=250, blank=True, null=True, default="")

在这个 ORM 查询之后

class BaseView(View):
    data = dict()
    template = "index.html"
    def get(self, request):
        self.data['coefficents_and_game'] = GameCoefficient.objects.all().select_related('game')
        return render_to_response(self.template, self.data)

我能够得到系数并显示他们的游戏。现在在模板中显示重复 "game_code"。我发现很难显示游戏及其系数。

将 Game QuerySet 发送到模板可能更容易:

class BaseView(View):
    data = dict()
    template = "index.html"
    def get(self, request):
        self.data['games'] = Game.objects.prefetch_related('gamecoefficient_set').all()
        return render_to_response(self.template, self.data)

使用如下模板:

{% for game in games %}
  {{ game.game_code }}
  {% for coeff in game.gamecoefficient_set.all %}
    {{ coeff.value }}
  {% endfor %}
{% endfor %}

更新:为数据库查询优化添加了prefetch_related