尝试找出最常见的前五个条目

1 投票
3 回答
909 浏览
提问于 2025-04-17 10:59

我正在尝试从我的查询中找出受伤最严重的球员,但我在获取正确结果时遇到了困难。

我在想把球员的ID放在一个列表里,但我该怎么数重复的条目,然后生成一个“前五名”受伤球员的列表呢?

这是我的models.py

class PlayerInjury(models.Model):
    player =  models.ForeignKey(Player)
    injury_type = models.ForeignKey(Injury)
    injury_date = models.DateField(verbose_name='Injured On', null=True, blank=True)
    description = models.CharField(verbose_name='Description', max_length=180, null=True, blank=True)
    status = models.ForeignKey(Status)
    projected_return = models.DateField(verbose_name='Projected Return Date', null=True, blank=True)
    hide = models.BooleanField(default=False)
    returned = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

这是我目前在views.py中的代码
编辑

def home(request):
context={}
player_list = []
most_recent = PlayerInjury.objects.all().order_by('-timestamp')[:5]
news = News.objects.all()
most_injured = PlayerInjury.objects.annotate(injury_count=Count('id')).order_by('-injury_count')[:5]
context['most_injured'] = most_injured
context['most_recent'] = most_recent
context['news'] =  news
return render_to_response('dash/home.html', RequestContext(request, context))

3 个回答

1

使用一个字典,把玩家的名字当作键,把玩家受伤的次数当作值。然后遍历你的数据,每当记录到一次受伤,就把对应的字典里的值加一。

在这个场景中使用字典的主要概念是:

字典中的键是唯一的,而值可以重复。字典的值可以是任何类型,但键必须是不可变的数据类型,比如字符串、数字或元组。

如果你想找出受伤次数最多的前5名玩家,可以对字典按值进行排序,生成一个列表。

2

如果你在使用2.7版本,一个纯Python的解决方案是

from collections import Counter
inj_counts = Counter()
for ip in all_intered_players:
    inj_counts[ip.player_id] += 1
inj_counts.most_common(5) # gives you a list of top five [(player_id, num_injuries), ...]

不过,使用Django的注释功能可能更好一些;这样大部分的计算工作会在你的数据库中完成。

4

为什么不直接使用注解呢?

from django.db.models import Count

Player.objects.annotate(injury_count=Count('playerinjury')).order_by('-injury_count')[:5]

撰写回答