[Django]-Django get query execution time

11👍

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'])

3👍

You can find the info in django.db.connection.queries.

3👍

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.

Leave a comment