2011-06-22 39 views
25

顶的X元素,我有两个型号,使得查询了在Django

class JobTitle(models.Model): 
    name = models.CharField(max_length=1000) 

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

正如你看到的,一个雇主可能有许多jobtitles。我尝试做一个查询,以获得职位数最多的前5名雇主

我该如何实现这个是Django?

感谢

+1

在这种模式下,一个人如何雇主可以有多个工作职位?雇主的其余领域在哪里?这只是一个外键? –

+0

@ SeanEd-Man我想他的意思是很多'雇主'可以有相同的'JobTitle'。 – h4k1m

回答

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

DOCS - > https://docs.djangoproject.com/en/1.11/topics/db/aggregation/ –

+1

甚至更​​好:https://docs.djangoproject.com/en/dev/topics/db/aggregation/ – Anupam

3
from django.db.models import Count 

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

你只需在“Employer”表中对行进行计数。你需要分组。 – DrTyrsa