Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of occurrences + count in a model Django?

Tags:

django

Imagine I have the following model:

class Person(models.Model):
    ...other stuff...
    optional_first_name= models.CharField(max_length=50, blank=True)

How would I go about writing a request that returns an array of the most popular names, in decreasing order of occurence, with their counts, while ignoring the empty names?

i.e. for a database with 13 Leslies, 8 Andys, 3 Aprils, 1 Ron and 18 people who haven't specified their name, the output would be:

[('leslie', 13), ('andy', 8), ('april', 3), ('ron', 1)]

The closest I can get is by doing the following:

q= Person.objects.all()
q.query.group_by=['optional_first_name']
q.query.add_count_column()
q.values_list('optional_first_name', flat= True)

But it's still not quite what I want.

like image 404
bitgarden Avatar asked Oct 10 '12 04:10

bitgarden


1 Answers

After some digging, finally found out:

Person.objects.values('optional_first_name').annotate(c=Count('optional_first_name')).order_by('-c')
like image 137
bitgarden Avatar answered Nov 11 '22 09:11

bitgarden