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.
- [Django]-Python django rest framework. How to serialize foreign key UUID in some specific format?
- [Django]-Python manage.py runserver: TypeError: argument 1 must be str not WindowsPath
- [Django]-Django Authenticate always returns None with correct credentials also
- [Django]-Django Rest Framework IsAuthenticated permission Error Anonymous user
- [Django]-How to configure code completion for Django based projects in PyDev?