Get SQL query count during a Django shell session
Solution 1
You can use connection.queries
:
>>> from django.conf import settings
>>> settings.DEBUG = True
>>> from django.db import connection
>>> Model.objects.count()
>>> print(len(connection.queries))
1
Solution 2
This is a slight improvement on the accepted answer. create a python file named extra_imports.py in some app (Eg some_app
)
extra_imports.py
from django.conf import settings
settings.DEBUG = True
from django.db import connection, reset_queries
def num_queries(reset=True):
print(len(connection.queries))
if reset:
reset_queries()
Now, If you are using shell_plus from django_extension (btw check it out if you are not using it), add following line to settings.py
SHELL_PLUS_PRE_IMPORTS = [('some_app.extra_imports', '*')]
If you are using django shell, run this inside shell
exec(open('some_app/extra_imports.py').read()) # python3
execfile('some_app/extra_imports.py').read()) # pyhton2
Or you can just paste the contents of extra_import.py
into the shell
Now,
In [1]: User.objects.all()
In [2]: num_queries()
1
In [3]: User.objects.filter(company=Company.objects.first()).all()
In [4]: num_queries()
2
Solution 3
If you have database routing and multiple connections, it's a bit trickier to count your database hits because connection.queries
considers only the default connection, as far as I can tell.
To include all connections:
from django.db import connections,connection,reset_queries
from django.conf import settings
settings.DEBUG = True
...
def query_count_all()->int:
query_total = 0
for c in connections.all():
query_total += len(c.queries)
return query_total
or more concisely:
def query_count_all()->int:
return sum(len(c.queries) for c in connections.all())
reset_queries()
already handles multiple connections
Jian
Updated on July 08, 2022Comments
-
Jian almost 2 years
Is there a way to print the number of raw SQL queries performed by the Django ORM during a Django shell session?
This sort of information is already provided by the Django debug toolbar (e.g,
5 QUERIES in 5.83MS
but it's not obvious how to get it from the shell. -
Romuald Brunet over 7 yearsUnfortunately that doesn't seem to work with Django 1.5, query count stays at 0
-
kjagiello over 6 yearsTried this method using Django 1.11 and it worked perfectly fine!
-
rschwieb about 6 yearsOne of my go-to's. Also useful with this:
django.db.reset_queries
to reset that count. -
rrauenza over 5 yearsNote, this stops counting at 9000. See
BaseDatabaseWrapper.queries_limit
-
Antimony over 4 yearsThis doesn't work for me, even in Django 1.11. I had to use Tim Richardson's answer to get the connection with the actual queries.
-
Josiah about 3 yearsRecently was linked to me by a friend after I'd started going this way: docs.djangoproject.com/en/3.1/topics/db/instrumentation