[英]Trying to find top 5 most common entries
我正在嘗試從查詢中找到受傷最嚴重的球員,但我無法獲得正確的結果。
我當時正在考慮將玩家ID放在列表中,但是如何計算重復的條目,然后生成“前5名”傷勢最嚴重的列表?
這是我的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)
以及到目前為止我的觀點。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))
為什么不只使用注釋 ?
from django.db.models import Count
Player.objects.annotate(injury_count=Count('playerinjury')).order_by('-injury_count')[:5]
如果您使用的是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的注釋功能可能更可取; 然后,繁重的工作就會在您的數據庫中發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.