[Answer]-Django aggregate, annotate with range

1👍

The query you’ve written is represented in SQL by something like

select sum(model_qty) from sold where sold_date > '2014-01-01' and sold_date < '2014-01-31'

This is already as optimised as you’re likely to get it (unless there are some database specific optimisations you can do), so any performance problems you’re experiencing are more likely caused by the number of queries.

I’m guessing, though, that you haven’t actually profiled it or run the query with live data to test performance. I suggest that you do that (with the debug toolbar for reporting) before you try to optimise your code too much. Its very likely you’ll find that the bottlenecks are elsewhere.

Leave a comment