Getting the SQL from a Django QuerySet


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.

9/20/2010 2:11:54 AM

Accepted Answer

You print the queryset's query attribute.

>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"
5/10/2019 12:07:19 PM


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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow