[Django]-How to force django to print each executed sql query

8👍

You can use django testing tools to capture queries on a connection. Assuming the default connection, something like this should work:

from django.db import connection
from django.test.utils import CaptureQueriesContext

def f():
    with CaptureQueriesContext(connection) as queries:
        # ...
        # many many python code
        # ...
    print(len(queries.captured_queries))

Note that this will only work in debug mode (settings.DEBUG = True), because it relies on the engine catpuring the queries. If you are using more than one connection, simply substitute the connection you are interested in.

If you are interested in the detail of queries, queries.captured_queries contains detailed information: the sql code, the params and the timings of each request.

Also, if you need to count queries while building test cases, you can simply assert the number, like this:

def test_the_function_queries(self):
    with self.assertNumQueries(42):  # check the_function does 42 queries.
        the_function()

If the test fails, Django will print all the queries for you to examine.

0👍

I would recommend the excellent django-debug-toolbar package. It allows you to interactively examine the SQL statements executed in a view, and even provides profiling information.

You can get it from pip:

pip install django-debug-toolbar

Include it in your settings.INSTALLED_APPLICATIONS:

INSTALLED_APPS = (
    # ...
    'django.contrib.staticfiles',
    # ...
    'debug_toolbar',
)

When executing your project in with DEBUG=True you should see a DjDT button in the top right corner.

Expanding the SQL tab will give you a detailed list of the sql queries.

enter image description here

Leave a comment