Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force django to print each executed sql query

Tags:

python

django

I have some function written with python. I want to know all sql queries, that was executed within this function. Is there a way to code something like:

def f():
    start_to_print_queries()

    # ...
    # many many python code
    # ...

    stop_to_print_queries()

?

like image 589
drlexa Avatar asked Dec 28 '25 05:12

drlexa


1 Answers

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.

like image 58
spectras Avatar answered Dec 30 '25 18:12

spectras