[Answered ]-Django select_related join model attributes with a single query

2👍

Your models are a little mind-twisting, but something like that should minimize the number of requests

from django.db.models import Q, F, Prefetch

... 

def get_context_data(self, **kwargs)
     context = super(FormationUpdateView, self).get_context_data(**kwargs)
     team = (Team.objects
     .select_related('league')
     .prefetch_related(
         Prefetch(
             'players',
             queryset=(Player.objects.filter(leagues=F('leagues'))
                       .prefetch_related('playerleagues'))
         )
     ).get(formations=self.kwargs['pk']))
     context['players'] = team.players.all()
     context['league'] = team.league
     return context

To get the stamina of a player without hitting the database again.

players[0].playerleagues.all()[0].stamina

Leave a comment