【问题标题】:Django query: Get states sorted by employee countDjango 查询:获取按员工人数排序的状态
【发布时间】:2013-09-26 18:55:07
【问题描述】:

我想使用 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)

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

【问题讨论】:

  • 不知道你的模型...
  • 那里,我添加了模型!

标签: django django-queryset django-orm


【解决方案1】:

解决了:

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

希望对他人有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多