James Lin
James Lin

Reputation: 26538

django filtering after aggregation

lets say I have a aggregation to show total number of orders of each sales rep created:

orders.values('sales_rep__username', 'sales_rep__email').annotate(Count('sales_rep'))

then how do I go about only select the sales reps have more than 100 orders created? Given the order table has too many records to iterate through code.

Note: I can only think about writing my own custom SQL statement, a colleague of mine came up a hack to use extra() method to inject a custom where subquery, but which isn't optimized for sql execution plan.

Upvotes: 0

Views: 117

Answers (1)

kjagiello
kjagiello

Reputation: 8410

Name the annotated value and use it in filter.

orders.values('sales_rep__username', 'sales_rep__email').annotate(order_count=Count('sales_rep')).filter(order_count__gt=100)

Upvotes: 1

Related Questions