1

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.

  • Can you describe the problem more in details? – Alexander Tyapkov Jan 10 '17 at 19:00
  • I discribe in russian version [link](http://ru.stackoverflow.com/questions/613180/select-related-%D0%9A%D0%B0%D0%BA-%D0%B2%D1%8B%D0%B2%D0%B5%D1%81%D1%82%D0%B8-%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D1%8C-%D0%BA-%D0%BA%D0%BE%D1%82%D0%BE%D1%80%D0%BE%D0%B9-%D0%BF%D1%80%D0%B8%D0%B2%D1%8F%D0%B7%D0%B0%D0%BD%D0%B0-%D0%B4%D1%80%D1%83%D0%B3%D0%B0%D1%8F-%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D1%8C-%D0%BF%D0%BE-foreignke) – Kamran XIDIROV Jan 10 '17 at 21:59
  • thanks. follow the answer of Jann. His solution looks good! – Alexander Tyapkov Jan 11 '17 at 08:47

1 Answers1

3

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

Jann
  • 1,799
  • 3
  • 21
  • 38
  • In this case how much queries will be sent to database? One or more? – Kamran XIDIROV Jan 10 '17 at 21:58
  • Good point. I added a prefetch_related which will fetch the related model and join them in python (s. http://stackoverflow.com/a/31237071/246028 for an explanation) – Jann Jan 10 '17 at 22:09