Is there a way I can print the query the Django ORM is generating?
Say I execute the following statement: Model.objects.filter(name='test')
How do I get to see the generated SQL query?
Is there a way I can print the query the Django ORM is generating?
Say I execute the following statement: Model.objects.filter(name='test')
How do I get to see the generated SQL query?
Each QuerySet object has a
query
attribute that you can log or print to stdout for debugging purposes.Edit
I've also used custom template tags (as outlined in this snippet) to inject the queries in the scope of a single request as HTML comments.
Maybe you should take a look at
django-debug-toolbar
application, it will log all queries for you, display profiling information for them and much more.You can use a Django debug_toolbar to view the SQL query. Step by step guide for debug_toolbar usage :
Install the Debug_toolbar
Edit settings.py file & add debug_toolbar to Installed apps, this should be added below to 'django.contrib.staticfiles'. Also add debug_toolbar to Middleware.
Settings.py=>
create a new list named INTERNAL_IPS in settings.py file
Settings.py=> create new list at the end of settings.py file & add below list:
This will allow the debug to run only on internal developement server
Edit urls.py file of #Project & add below code:
apply migrate & run server again
You will see an add-on on your web page at 127.0.0.1 & if you click on SQL Query check box, you can actually see the run time of query as well.
A robust solution would be to have your database server log to a file and then
As long as
DEBUG
is on:For an individual query, you can do:
You also can use python logging to log all queries generated by Django. Just add this to your settings file.
Another method in case application is generating html output - django debug toolbar can be used.