I have table invoices with field customer_id and some others fields. I need select count of purchases, taken by each user. In SQL it’s should looks like this:
SELECT username, COUNT('customer_id') FROM `invoices`
LEFT JOIN `auth_user` ON `auth_user`.id = `invoices`.customer_id
GROUP BY `customer_id`, username
In Django i try:
Invoice.objects.annotate(buy_count=Count('customer')).all()
But this code groups by invoices.id instead of invoices.customer_id and returns wrong result.
I think you should turn it around, something like:
There you’d get a list of Customer with their count of invoice.