How can I see the raw SQL queries Django is running?
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.
If you need to reset the queries to, for example, see how many queries are running in a given period, you can use reset_queries
from django.db
:
from django.db import reset_queries
reset_queries()
print(connection.queries)
>>> []
Django-extensions have a command shell_plus with a parameter print-sql
./manage.py shell_plus --print-sql
In django-shell all executed queries will be printed
Ex.:
User.objects.get(pk=1)
SELECT "auth_user"."id",
"auth_user"."password",
"auth_user"."last_login",
"auth_user"."is_superuser",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."date_joined"
FROM "auth_user"
WHERE "auth_user"."id" = 1
Execution time: 0.002466s [Database: default]
<User: username>