Query for top x elements in Django

若如初见. 提交于 2020-01-22 17:03:26

问题


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


回答1:


Employer.objects.values('id').annotate(jobtitle_count=Count('jobtitle')).order_by('-jobtitle_count')[:5]



回答2:


from django.db.models import Count

Employer.objects.annotate(Count('jobtitle')).order_by('-jobtitle__count')[:5]


来源:https://stackoverflow.com/questions/6436937/query-for-top-x-elements-in-django

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