Reputation: 75
Is there a way to measure Django query time without using django-debug-toolbar? It is not for debugging/logging, I need it to display on the webpage like about # results (# seconds)
.
Edit: I need this feature in production mode, so DEBUG=True
is not an option
Upvotes: 3
Views: 11923
Reputation: 21812
Although django.db.connection.queries
will give you the query times it only works when DEBUG=True
. For using it for general purposes we can work with Database instrumentation [Django docs] and write a wrapper that will time our queries. Below is the example directly from the above documentation which I would say seems to fit your need:
import time
class QueryLogger:
def __init__(self):
self.queries = []
def __call__(self, execute, sql, params, many, context):
current_query = {'sql': sql, 'params': params, 'many': many}
start = time.monotonic()
try:
result = execute(sql, params, many, context)
except Exception as e:
current_query['status'] = 'error'
current_query['exception'] = e
raise
else:
current_query['status'] = 'ok'
return result
finally:
duration = time.monotonic() - start
current_query['duration'] = duration
self.queries.append(current_query)
To use this you would make your queries in such a way:
from django.db import connection
query_logger = QueryLogger()
with connection.execute_wrapper(query_logger):
# Make your queries here
for query in query_logger.queries:
print(query['sql'], query['duration'])
Upvotes: 13
Reputation: 2380
You can do this :
if DEBUG=True
in settings.py
, you can see your database queries (and times) using:
>>> from django.db import connection
>>> connection.queries
P.s: There is a package called django-debug-toolbar which helps you so much to see your queries and timings and so on ... . I recommend to use it instead of connection.queries
.
Upvotes: 3