Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query for top x elements in Django

I have two models such that

class JobTitle(models.Model):      name = models.CharField(max_length=1000)  class Employer(models.Model):       jobtitle = models.ForeignKey(JobTitle,unique=False,null=True) 

As you see, one employer may have many jobtitles. I try to make a query to get top 5 employers whose number of job titles is maximum

How can I achive this is Django ?

Thanks

like image 956
brsbilgic Avatar asked Jun 22 '11 08:06

brsbilgic


2 Answers

Employer.objects.values('id').annotate(jobtitle_count=Count('jobtitle')).order_by('-jobtitle_count')[:5] 
like image 114
DrTyrsa Avatar answered Oct 21 '22 20:10

DrTyrsa


from django.db.models import Count  Employer.objects.annotate(Count('jobtitle')).order_by('-jobtitle__count')[:5] 
like image 30
Jj. Avatar answered Oct 21 '22 19:10

Jj.