Debugging django SQL perfonmance

Recently I had a conversation with one of our developers about site speed & dependency on amount of queries per page. I strongly believe that any kind of SQL query, executed per object, leads to a aggressive speed problems, in future.

Also, that normally shows that object oriented approach sometimes does not work well with Web concepts. For a big listings on page, we should fetch a list of objects with their attributes once, in single SQL query. That makes linear dependency between page rendering speed and amount of data.

But now the question comes - how can we see the amount & time of SQL queries are going on? The answer comes with Django Snipped #161 and which is being integrated into our package DjHDGutils

To start debugging SQL queries for particular page rendering

Add the following line to your settings.py file:

MIDDLEWARE_CLASSES += ('DjHDGutils.profiling.SQLLogMiddleware',)

Results to analyze

Normally, all duplicated queries must be turned into single call. That often requires changing ORM query to a direct SQL query for data. Here is example of data you would see after enabling this profiler: