5

In my django application, I have a set of donation, which I want to make statistics on. For each donation, a person is linked with his email address.

I want to compute for each month, the number of donors, that is the number of unique email addess.

So far I have:

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

This works well, I get a monthly report of all email donors, but as I got duplicate in email, it does not filter email by unique values.

The current database used is Postgresql.

How this can be done?

2
  • Are you using postgres? Commented May 12, 2016 at 9:13
  • Yes, I'll add this in the question. Commented May 12, 2016 at 9:14

1 Answer 1

7

Count takes a distinct argument, so you can do:

donors = qs.values('month').annotate(count=Count('email', distinct=True)).order_by('month')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.