How to see the raw SQL queries Django is running?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island
--
Chapters
00:00 Question
00:19 Accepted answer (Score 546)
01:35 Answer 2 (Score 106)
02:10 Answer 3 (Score 69)
02:28 Answer 4 (Score 40)
02:42 Thank you
--
Full question
https://stackoverflow.com/questions/1074...
Accepted answer links:
[How can I see the raw SQL queries Django is running?]: http://docs.djangoproject.com/en/stable/...
[query]: https://docs.djangoproject.com/en/stable...
[#17741]: https://code.djangoproject.com/ticket/17...
Answer 2 links:
[Django-extensions]: https://pypi.python.org/pypi/django-exte.../
[shell_plus]: http://django-extensions.readthedocs.org...
Answer 3 links:
http://django-debug-toolbar.readthedocs..../
[image]: https://i.stack.imgur.com/VR75R.png
--
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.
