Django ORM select_related渲染模板

时间:2017-01-10 18:32:55

标签: django django-models django-templates django-orm django-select-related

我在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”。我发现很难显示游戏及其系数。

1 个答案:

答案 0 :(得分:2)

您可能更容易将游戏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 %}

更新:为db-query optimization添加了prefetch_related