[Fixed]-How to time Django queries

6👍

The debug toolbar is what you want, it helps you time each of your queries.

Alternatively this snippet works too.

http://djangosnippets.org/snippets/93/

👤bdd

30👍

if your django project is in debug, you can see your database queries (and times) using:

>>> from django.db import connection
>>> connection.queries

I know this won’t satisfy your need to profile functions, but hope it helps for the queries part!

👤Brosto

6👍

The best way you can get is by using Debug Toolbar, you will also get some additional functionalities for Query optimization, which will help you to optimize your db query.

Here is another solution, You can use connection.queries. This will return the SQL command has been made for the command which was executed just before the connect.queries command. You can the reset_queries after getting the time of the previous query by using reset_queries(). Using reset_queries() is not mandatory.

Suppose you have a Model named Device. You can measure the query time like this:

>>> from django.db import connection, reset_queries
>>> from appname.models import Device
>>> devices = Device.objects.all()
>>> connection.queries
>>> reset_queries()

1👍

Anyone stumbling on to this checkout Sentry’s approach.

https://github.com/getsentry/sentry-python/blob/master/sentry_sdk/integrations/django/__init__.py#L476

You can replace execute and executemany with your owns functions that track the time it takes for execute to return.

A simple approach is to create custom context manager that initiates a timer and on exit writes final value of the timer to an array you pass to it.

Then you can just check the array.

Leave a comment