Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to time Django queries

Tags:

timeit

django

I've always used Python's timeit library to time my little Python programs. Now I'm developing a Django app and I was wondering how to time my Django functions, especially queries.

For example, I have a def index(request) in my views.py which does a bunch of stuff when I load the index page. How can I use timeit to time this particular function without altering too much my existing functions?

like image 341
chiurox Avatar asked Dec 09 '10 17:12

chiurox


People also ask

What is query optimization in Django?

The main goal of optimization in Django projects is to make it fast to perform database queries by ensuring that your projects run by making the best use of system resources. A properly optimized database will reduce the response time hence a better user experience.

How do I query in Django?

You get a QuerySet by using your model's Manager . Each model has at least one Manager , and it's called objects by default. Access it directly via the model class, like so: >>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name='Foo', tagline='Bar') >>> b.objects Traceback: ...

What is Prefetch_related in Django?

In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects. In this article, we will see how it reduces the number of queries and make the program much faster.


2 Answers

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()
like image 105
Farid Chowdhury Avatar answered Sep 27 '22 21:09

Farid Chowdhury


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!

like image 42
Brosto Avatar answered Sep 27 '22 22:09

Brosto