2016-05-12 89 views
5

在我的django应用程序中,我有一组捐赠,我想对其进行统计。对于每次捐赠,一个人都与他的电子邮件地址相关联。Django queryset group by和count的区别

我想计算每个月的捐助者数量,即唯一的电子邮件地址的数量。

到目前为止,我有:

# filter all donations by month 
truncate_date = connection.ops.date_trunc_sql('month', 'date') 
qs = Donation.objects.extra({'month': truncate_date}) 

# group by months and annotate each with the count of emails 
donors = qs.values('month').annotate(count=Count('email')).order_by('month') 

这种运作良好,我得到的所有电子邮件捐助者的月度报告,但我得到了电子邮件复制,它不唯一值过滤电子邮件。

当前使用的数据库是Postgresql。

这是怎么做到的?

+0

是否使用Postgres的? – Sayse

+0

是的,我会在问题中加上这个。 – nobe4

回答

5

Count需要distinct argument,所以你可以做:

donors = qs.values('month').annotate(count=Count('email', distinct=True)).order_by('month')