Django queryset group by 和 count distincts
Django queryset group by and count distincts
在我的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')
这很好用,我收到了所有电子邮件捐助者的月度报告,但由于我在电子邮件中收到重复项,它不会按唯一值过滤电子邮件。
当前使用的数据库是Postgresql
如何做到这一点?
Count
需要一个distinct
argument,所以你可以这样做:
donors = qs.values('month').annotate(count=Count('email', distinct=True)).order_by('month')
在我的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')
这很好用,我收到了所有电子邮件捐助者的月度报告,但由于我在电子邮件中收到重复项,它不会按唯一值过滤电子邮件。
当前使用的数据库是Postgresql
如何做到这一点?
Count
需要一个distinct
argument,所以你可以这样做:
donors = qs.values('month').annotate(count=Count('email', distinct=True)).order_by('month')