【问题标题】:Counting number of occurrences in Foreign Key relationships计算外键关系中出现的次数
【发布时间】:2016-10-01 13:01:36
【问题描述】:

我设置了以下模型:

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)

任何帮助将不胜感激

【问题讨论】:

  • 最好将您的问题的答案发布为答案,而不是编辑以分享 Q/A 风格以供将来可能遇到同样问题的人使用。
  • 好的,我会这样做的。
  • 是的,我在这个问题上遗漏了一些类似的东西。到目前为止,从我的测试用例中一切正常。

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


【解决方案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()

【讨论】:

  • 虽然这个答案可能有效,但它将成为数据库杀手。请注意您是如何从获取所有 Match 对象开始的。如果有数十万条记录,您将获得大量数据。其次注意你是如何有一个嵌套循环的。在你的嵌套循环中,你正在做一个嵌套循环。嵌套循环很少是获取数据的正确解决方案
  • 您会推荐什么?我可能会有 70-110,000 个匹配表条目,我使用的是 MariaDB/MySQL 而不是 SQLite。
  • 贴出真实模型,我会尝试破解它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
相关资源
最近更新 更多