Trying to find top 5 most common entries

大城市里の小女人 提交于 2019-12-08 09:56:55

问题


I am trying to find the most injured player from my query but I am having trouble getting the proper results.

I was thinking of putting the player ID's in a list but how do you go about counting duplicate entries and then producing a "top 5" most injured list?

Here is my 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)

and what I have so far for my views.py
EDIT

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))

回答1:


Why not just use annotations?

from django.db.models import Count

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



回答2:


If you're using 2.7, a pure-python solution would be

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), ...]

Although using django's annotation feature is probably more advisable; the heavy lifting will then happen in your database.




回答3:


Use a dictionary where the key is the player's name and the value is a counter of how many times the player got hurt. Iterate over your data and increment each dictionary entry's value on any instance of injury.

They main concept in using a dictionary in this scenario:

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

To get your top 5 you could then produce a list that is a sort of the dictionary by value.



来源:https://stackoverflow.com/questions/8991919/trying-to-find-top-5-most-common-entries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!