【问题标题】:Django query User growth by monthDjango按月查询用户增长
【发布时间】:2016-04-25 20:21:28
【问题描述】:

有没有办法使用 Django ORM 根据按年/月分组的 date_joined 获取 User count()?

我能够在我的 Django/Postgres 项目中使用原始 SQL 获取这些数据,如下所示:

from django.db import connection
...    
    cursor = connection.cursor()
    cursor.execute('''
        SELECT
            to_char(date_joined, 'YYYY/MM') as month,
            cast(count(id) as int) as total
        FROM users_user
        GROUP BY month 
        ORDER BY month DESC
        ''')

返回给我的列表如下: [('2015/12', 105), ('2016/01' , 78), ('2016/02', 95)...]

【问题讨论】:

    标签: django postgresql django-orm


    【解决方案1】:

    试试:

    from django.contrib.auth.models import User
    from django.db.models import Count
    
    User.objects.all() \
            .extra({'created': "to_char(date_joined, 'YYYY/MM')"}) \
            .values('created') \
            .annotate(created_count=Count('id')) \
            .order_by('-created')
    

    【讨论】:

    • 如果你使用 `\` 作为续行,如果你有尾随空格,它将中断。请改用括号。
    【解决方案2】:

    在 django 1.10+ 中,您可以使用以下内容:

    from django.contrib.auth.models import User
    from django.db.models import Count
    from django.db.models.functions import TruncMonth
    
    
    User.objects.all() \
        .annotate(month=TruncMonth("date_joined")) \
        .values("month") \
        .annotate(c=Count("id")) \
        .order_by("-month")
    

    在后台,ahmed 给出的答案将转换为以下 SQL:

    SELECT ( To_char(date_joined, 'YYYY/MM') ) AS "created", 
           Count("users_user"."id")            AS "created_count" 
    FROM   "users_user" 
    GROUP  BY ( To_char(date_joined, 'YYYY/MM') ) 
    ORDER  BY "created" DESC 
    

    “较新”方法将运行以下 SQL:

    SELECT Date_trunc('month', "users_user"."date_joined" at time zone 
                               'Europe/London') AS 
           "month", 
           Count("users_user"."id") 
           AS "c" 
    FROM   "users_user" 
    GROUP  BY Date_trunc('month', "users_user"."date_joined" at time zone 
                                  'Europe/London') 
    ORDER  BY "month" DESC 
    

    但这在很大程度上无关紧要 - 性能呢?

    4,000 users:
        Method 1: 0.003886s
        Method 2: 0.005572s
    
    50,000 users:
        Method 1: 0.064483s
        Method 2: 0.040544s
    

    边际差异,但取决于您的用例/规模...

    【讨论】:

      猜你喜欢
      • 2016-10-17
      • 1970-01-01
      • 2014-10-24
      • 2021-12-24
      • 1970-01-01
      • 2014-03-08
      • 2019-09-05
      • 1970-01-01
      • 2014-06-14
      相关资源
      最近更新 更多