How can I count across several relationships in django How can I count across several relationships in django django django

How can I count across several relationships in django


Funny problem ! I think I have the answer (get the team that beats yourteams the most):

Team.objects.get( # the expected result is a team    pk=list( # filter out yourteams        filter(lambda x: x not in [ y.id for y in yourteams ],            list(                 Match.objects # search matches                .filter(matchteams__in=yourteams) # in which you were involved                .filter(matchteams__winner=False) # that you loose                .annotate(cnt=Count('teams')) # and count them                .order_by('-cnt') # sort appropriately                .values_list('teams__id', flat=True) # finally get only pks            )        )    )[0] # take the first item that should be the super winner)

I did not test it explicitly, but if does not work, I think it may be the right track.


You can do something like this

matches_won_aginst_my_team = MatchTeam.objects.filter(team=my_team, winner=False).select_related(matches)    teams_won_matches_aginst_my_team = matches_won_aginst_my_team.filter(winner=True).values_list('matchteams__team')

But as suggested you can probably model better.
I would hold two fields in the MatchModel: home_team, away_team.
Simpler and more indicative.