【问题标题】:How to count more than one fields and grouping them using django orm如何计算多个字段并使用 django orm 对它们进行分组
【发布时间】:2017-12-11 10:03:17
【问题描述】:

我是 Django 及其 ORM 的新手。

User 有很多用户。我需要对活跃用户和总数进行分组 表中的用户,我还需要根据他们使用 Django ORM 加入的年份对他们进行排序 在 sql 中,这可能是这样的,

select count('users'), 
count('users' where is_active is True as 'active_users') form user 
order by 'created_at'

【问题讨论】:

    标签: python sql django orm


    【解决方案1】:
    # Get all users include active users
    users = User.objects.all().order_by('created_at')
    users_count = users.count() 
    # Get only active users
    active_users = User.objects.filter(is_active=True).order_by('created_at')
    active_users_count = active_users.count()
    

    对表格中的活跃用户和总用户进行分组

    至于聚合,看这个answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-22
      • 2018-08-08
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多