Optimizations, using SQL for heavy operations rather than Python