I am optimizing a big part of my code so I am trying to reduce the database hits to the minimum and try to grab all necessary data in big but few queries and cache it.
However I have not found an effective way of seeing whether Django is actually running a query against the database or whether it is returning cached or prefetched data.
Ideally, I want to debug the relevant parts of my code line by line and each raw SQL query should be displayed as they are executed. Essentially some kind of listener that logs every query that is run as soon as it is run.
This way to check running queries suggested by the docs is not good enough, as it only displays queries formed in the same file where you access connection.queries
, apparently.
Accessing QuerySet.query
is no good either, as it requires a, well, QuerySet
object. There are other scenarios where queries are run against the database but the return type is not a QuerySet
.
I am not sure the Django Debug Toolbar would work either, because I don't want my behavior wrapped in a view, I want to execute an independent script and thoroughly debug it.