3

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()

?

2
  • 4
    Do you need it for something special, or is it just for debugging? Or for testcases?
    – spectras
    Nov 20, 2015 at 13:03
  • Because of django ORM I do not know how many sql queries was actually executed. I want to know this count.
    – drlexa
    Nov 20, 2015 at 13:12

2 Answers 2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.