python - Counting number of occurrences in Foreign Key relationships -
i have following models set up:
class team(models.model): # stuff class alliance(models.model): # alliance made of 3 teams teams = models.manytomanyfield(team) class match(models.model): # 2 alliances per match alliances = models.manytomanyfield(alliance) # 1 winner per match winner = models.foreignkey(alliance, related_name='winner')
i trying find teams , alliances have wins. have gotten alliances work through this:
from collections import counter def most_alliance_wins(): matches = match.objects.all() count = counter() m in matches: count[m.winner] += 1 # remove ties del count[none] return count.most_common(5)
however, teams wins method won't work, saying can't access manager model, i'm not sure in code i'm trying access manager, i'm bit lost.
from collections import counter def most_team_wins(): matches = match.objects.all() count = counter() m in matches: team in m.winner.objects.all(): count[team] += 1 return count.most_common(5)
any immensely appreciated
ah, i'm dumb. solved!
this solution:
def most_wins(): matches = match.objects.all() count = counter() m in matches: if m.winner none: continue team in m.winner.teams.all(): count[team] += 1 return count.most_common(5)
i should have been referencing m.winner.teams.all()
instead of m.winner.objects.all()
.