Optimizing Performance in Django: Eliminating Left Outer Joins with Subqueries and django-sql-utils

Dmytro Litvinov
1 min readFeb 26, 2023

I was having performance issues with my project and noticed that the SQL queries to the database through django-debug-toolbar were taking a long time. Upon investigating the queries, I found that a LEFT OUTER JOIN was causing the issue. I needed to add annotations to count the number of child instances associated with an instance.

Initially, the SQL query and custom queryset method were quite complex, so I rewrote it using Subquery to remove the LEFT OUTER JOIN. However, the new Django code was a bit harder to read, so I found the django-sql-utils library to simplify the code.

P.S. Thank you for reading my article! If you enjoyed it and would like to see more, please subscribe to my Telegram channel “The Software Sage” which is the main source for all my content.

--

--

Dmytro Litvinov

I am Software Developer | Writing about: 🐍 Python 💻 Software Development 💭 Practical tips and advice https://dmytrolitvinov.com