How to see the raw SQL queries Django is running?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 How To See The Raw Sql Queries Django Is Running?
00:15 Accepted Answer Score 575
01:26 Answer 2 Score 118
01:59 Answer 3 Score 71
02:17 Answer 4 Score 41
02:32 Answer 5 Score 35
03:05 Thank you
--
Full question
https://stackoverflow.com/questions/1074...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #sql #django #database #djangodatabase
#avk47
ACCEPTED ANSWER
Score 578
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
from django.db import connection
reset_queries()
# Run your query here
print(connection.queries)
>>> []
ANSWER 2
Score 71
Take a look at debug_toolbar, it's very useful for debugging.
Documentation and source is available at http://django-debug-toolbar.readthedocs.io/.
ANSWER 3
Score 42
The query is actually embedded in the models API:
q = Query.objects.values('val1','val2','val_etc')
print(q.query)
ANSWER 4
Score 36
I find by far the most useful, simple, and reliable method is to ask your database. For example on Linux for Postgres you might do:
sudo su postgres
tail -f /var/log/postgresql/postgresql-8.4-main.log
Each database will have slightly different procedure. In the database logs you'll see not only the raw SQL, but any connection setup or transaction overhead django is placing on the system.
