Django按月查询用户增长情况

时间:2016-04-25 20:21:28

标签: django postgresql django-orm

有没有办法根据使用Django ORM按年/月分组的User获得date_joined 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)...]

2 个答案:

答案 0 :(得分:2)

尝试:

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')

答案 1 :(得分:0)

在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

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