Django查询:获取按员工数排序的状态

时间:2013-09-26 18:55:07

标签: django django-queryset django-orm

我想使用Django ORM运行以下SQL查询。我不想使用原始sql,因为我想将它与另一个查询连接起来。

SELECT count(e.id), o.state
FROM core_employeemodel e, core_officemodel o
WHERE e.office_id = o.id
GROUP BY o.state 
ORDER BY -count(e.id);

型号:

class OfficeModel(Model):
    address1 = CharField('address 1', max_length=50,)
    address2 = CharField('address 2', max_length=50, blank=True)
    city = CharField('city', max_length=50, db_index=True)
    state = CharField('state', max_length=2, choices=STATE_CHOICES, db_index=True)
    zip_code = CharField('zip code', max_length=50, db_index=True)
    phone = CharField('phone', max_length=50,)
    fax = CharField('fax', max_length=50, blank=True)

class EmployeeModel(Model):
    first_name = CharField('first name', max_length=50, db_index=True)
    last_name = CharField('last name', max_length=50, db_index=True)
    picture = ImageField('picture', upload_to='employee_picture/', blank=True,)
    fax = CharField('fax', max_length=50, blank=True)
    email = EmailField('email', unique=True)

我尝试了注释但是没有得到好结果。你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

解决了它:

OfficeModel.objects.values('state').annotate(employee_cnt=Count('employee_office')).order_by('-employee_cnt')

希望它能帮助别人!