python – Getting the SQL from a Django QuerySet

The Question :

317 people think this question is useful

How do I get the SQL that Django will use on the database from a QuerySet object? I’m trying to debug some strange behavior, but I’m not sure what queries are going to the database. Thanks for your help.

The Question Comments :
  • This isn’t a duplicate. the linked question is quite a different topic.
  • @Wooble this isn’t a duplicate. It’s in the same area as the other question but this question relates to a specific query, not ALL queries.

The Answer 1

499 people think this answer is useful

You print the queryset’s query attribute.

>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"

The Answer 2

55 people think this answer is useful

Easy:

print my_queryset.query

For example:

from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query

It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:

from django.db import connections
connections['default'].queries

The django debug toolbar project uses this to present the queries on a page in a neat manner.

The Answer 3

51 people think this answer is useful

The accepted answer did not work for me when using Django 1.4.4. Instead of the raw query, a reference to the Query object was returned: <django.db.models.sql.query.Query object at 0x10a4acd90>.

The following returned the query:

>>> queryset = MyModel.objects.all()
>>> queryset.query.__str__()

The Answer 4

11 people think this answer is useful

This middleware will output every SQL query to your console, with color highlighting and execution time, it’s been invaluable for me in optimizing some tricky requests

http://djangosnippets.org/snippets/290/

The Answer 5

11 people think this answer is useful

As an alternative to the other answers, django-devserver outputs SQL to the console.

Add a Comment