djangodjango-ormdjango-testing

Django: how to count SQL queries from a unit test?


I am trying to find out the number of queries executed by a utility function. I have written a unit test for this function and the function is working well. What I would like to do is track the number of SQL queries executed by the function so that I can see if there is any improvement after some refactoring.

def do_something_in_the_database():
    # Does something in the database
    # return result

class DoSomethingTests(django.test.TestCase):
    def test_function_returns_correct_values(self):
        self.assertEqual(n, <number of SQL queries executed>)

EDIT: I found out that there is a pending Django feature request for this. However the ticket is still open. In the meantime is there another way to go about this?


Solution

  • Since Django 1.3 there is a assertNumQueries available exactly for this purpose.

    One way to use it (as of Django 3.2) is as a context manager:

    # measure queries of some_func and some_func2
    with self.assertNumQueries(2):
        result = some_func()
        result2 = some_func2()