Getting the SQL from a Django QuerySet

PythonSqlDjangoDjango Queryset

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

You print the queryset's query attribute.

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

Solution 2 - Python

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.

Solution 3 - Python

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__()

Solution 4 - Python

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/

Solution 5 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionexuperoView Question on Stackoverflow
Solution 1 - PythonjpwattsView Answer on Stackoverflow
Solution 2 - PythonMike AxiakView Answer on Stackoverflow
Solution 3 - PythonHakan B.View Answer on Stackoverflow
Solution 4 - PythonGuillaume EsquevinView Answer on Stackoverflow
Solution 5 - PythonTomasz ZielińskiView Answer on Stackoverflow