Search code examples
djangodjango-modelsdjango-templatesdjango-ormdjango-select-related

Django ORM select_related rendering template


I have this models in Django 1.10 version

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="")

after this ORM query

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)

I was able to get the coefficients and display their games. Now in template displays repeating "game_code". I find it difficult to display the game and its coefficients.


Solution

  • It might be easier for you to send the Game QuerySet to the template instead:

    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)
    

    Using a template like:

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

    Update: Added prefetch_related for db-query optimisation