Search code examples
pythondjango

Is there a way to log the total number of queries made in a django view?


I have non-traditional view that responds to an ajax request. Usually, I use the debug toolbar to get the query count, however, since this particular view is simply returning some json, there's no page for the Debug Toolbar to display itself.

Is there a way to print out the total queries executed in the view to the console?

From browsing the docs, is found qs.query. However, that just gives what my base orm lookup will be. I'm really looking for the sum total from everything that happens in my view (for instance, additional queries triggered from traversing foreign keys).


Solution

  • You can write a middleware for this purpose:

    from django.db import connection
    
    
    class SqlPrintMiddleware(object):
        def process_response(self, request, response):
            sqltime = 0 # Variable to store execution time
            for query in connection.queries:
                sqltime += float(query["time"])  # Add the time that the query took to the total
     
            # len(connection.queries) = total number of queries
            print "Page render: " + unicode(sqltime) + "sec for " + unicode(len(connection.queries)) + " queries"
     
            return response
    

    And in your settings.py change:

    MIDDLEWARE_CLASSES = (
        # ...
        'your_app.middleware.SqlPrintMiddleware',
        # ...
    )
    

    Idea was taken from here