2016-04-25 89 views
0

有沒有辦法根據使用Django ORM按年/月分組的date_joined得到User count()的方法?Django查詢用戶按月增長

我能得到我的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

嘗試:

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

如果你使用'\\'作爲續行,如果你有尾隨空格,它將會中斷。改用括號。 –