Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing Django DB Queries

I'm attempting to benchmark the speed of several different queries which return the same thing on Django 1.4 with Postgres. Unfortunately, if I use:

 import logging
 l = logging.getLogger('django.db.backends')
 l.setLevel(logging.DEBUG)
 l.addHandler(logging.StreamHandler())

Two equivalent or similar queries, end up getting deferred to the Query cache. Any way I can clear this cache or have a better way of comparing the speed of two queries?

like image 936
zhuyxn Avatar asked Jul 19 '13 05:07

zhuyxn


People also ask

Why Django queries are slow?

If you're experiencing slowness with the second line, the problem is eitherwith the actual execution of the query, or with the display\printing of the data. You can force-execute the query without printing it (check the documentation) to find out which one it is.

Are Django queries lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.

How can you see raw SQL queries running in Django?

Django gives you two ways of performing raw SQL queries: you can use Manager. raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly. Explore the ORM before using raw SQL!


1 Answers

For my analysis I used something like this:

from django import db
for query in db.connections['default'].queries:
    print query, query['time']
like image 102
steffens21 Avatar answered Sep 30 '22 15:09

steffens21