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

标签 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)

但是,我的团队 wins 方法不起作用,说我无法访问模型的管理器,但我不确定代码中我实际尝试访问管理器的位置,所以我'我有点迷茫。

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)

任何帮助将不胜感激

最佳答案

啊,我傻了。解决了!

这是解决方案:

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()

关于python - 计算外键关系中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37580880/

相关文章:

python - 如何将元组转换为元组列表?

Django:IntegrityError 列 'user_id' 不能为空

django - Django 中实现的 ON DELETE CASCADE 逻辑在哪里? (使用的是PostgreSQL)

python-3.x - 使用 python3 和 mod_wsgi(无 Django)的基本 Web 表单示例?

python - 如何告诉cgi停止等待

python - 为查询集的下标元素赋值不起作用

python - 用户输入的输出字典不正确

python - 将当前列名称更改为行并替换为其他列名称

python - print() 函数的结束参数

python - 重新装箱时保留 FITS 文件的 WCS 信息