2👍
Always base your query around the object in which you are primarily interested in:
repeat_customers = Customer.objects.annotate(order_count=Count('order'))\
.filter(order_count__gt=1)
Then if you want to annotate with their totals (you could alternatively do this in the annotation above, I’m just separating the code for readability):
repeat_customers = repeat_customers.annotate(avg_total=Avg('order__total'))
0👍
This would be a good use for Django 1.1’s annotate()
functionality, which is part of aggregateion. Specifically, you’ll probably want to use the values()
function.
Source:stackexchange.com