尝试找出最常见的前五个条目
我正在尝试从我的查询中找出受伤最严重的球员,但我在获取正确结果时遇到了困难。
我在想把球员的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 个回答
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]