Django version 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="") 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) When rendering, I get a GameCoefficient and a ForeignKey GAME while the template gets the GameCoefficient model and if I do
{% for item in coefficents_and_game %} {{item.game}} {% endfor %} In this case, the game code (game_code) is repeated by the number of GameCoefficient, and I need ONE request to display Game and GameCoefficient. But according to the Game table, the associated GameCoefficient table.
{% for game in coefficents_and_game %} {{game.game_code}} {% for coefficient in game %} {{coefficient.win_type}} {{coefficient.value}} {% endfor %} {% endfor %} By reading this, you can make one of these "select_related" statements, "fetch_reverse_relations", "prefetch_related", but I couldn’t fully understand the difference between them in order to achieve the result and output the query example in reverse order.