Django queryset group by和count的区别

nob*_*be4 5 python django django-models django-queryset

在我的django应用程序中,我有一组捐款,我想对其进行统计.对于每次捐赠,一个人与他的电子邮件地址相关联.

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

到目前为止,我有:

# 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')
Run Code Online (Sandbox Code Playgroud)

这很好,我得到了所有电子邮件捐赠者的月度报告,但由于我在电子邮件中有重复,它不会按唯一值过滤电子邮件.

使用的当前数据库是Postgresql.

怎么做到这一点?

sol*_*oke 5

Count采取distinct参数,所以你可以这样做:

donors = qs.values('month').annotate(count=Count('email', distinct=True)).order_by('month')
Run Code Online (Sandbox Code Playgroud)