简体   繁体   中英

Trying to find top 5 most common entries

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

Why not just use annotations ?

from django.db.models import Count

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM