简体   繁体   中英

Django get query execution time

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

您可以在django.db.connection.queries找到信息。

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

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  

Ps : 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM