我设置了以下模型:
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/