簡體   English   中英

嘗試找到最常見的5個條目

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM