计算外键关系中出现的次数

时间:2016-06-02 00:32:34

标签: python django python-3.x count django-queryset

我设置了以下型号:

class Team(models.Model):
    # stuff

class Alliance(models.Model):
    # an alliance is made up 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')

我正在努力寻找哪些球队和联盟获胜最多。我成功地结成了联盟:

from collections import Counter
def most_alliance_wins():
    matches = Match.objects.all()
    count = Counter()
    for m in matches:
        count[m.winner] += 1
    # Remove ties
    del count[None]
    return count.most_common(5)

但是,我的团队胜利方法不会工作,说我无法访问该模型的经理,但我不确定代码中我在哪里尝试访问经理,所以我有点迷失。

from collections import Counter
def most_team_wins():
    matches = Match.objects.all()
    count = Counter()
    for m in matches:
        for team in m.winner.objects.all():
            count[team] += 1
    return count.most_common(5)

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

啊,我很蠢。解决!

这是解决方案:

def most_wins():
    matches = Match.objects.all()
    count = Counter()
    for m in matches:
        if m.winner is None:
            continue
        for team in m.winner.teams.all():
            count[team] += 1
    return count.most_common(5)

我应该引用m.winner.teams.all()而不是m.winner.objects.all()