How can I see the raw SQL queries Django is running?

spence91 picture spence91 · Jul 2, 2009 · Viewed 187k times · Source

Is there a way to show the SQL that Django is running while performing a query?

Answer

geowa4 picture geowa4 · Jul 2, 2009

See the docs FAQ: "How can I see the raw SQL queries Django is running?"

django.db.connection.queries contains a list of the SQL queries:

from django.db import connection
print(connection.queries)

Querysets also have a query attribute containing the query to be executed:

print(MyModel.objects.filter(name="my name").query)

Note that the output of the query is not valid SQL, because:

"Django never actually interpolates the parameters: it sends the query and the parameters separately to the database adapter, which performs the appropriate operations."

From Django bug report #17741.

Because of that, you should not send query output directly to a database.