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.
qs = Model.objects.filter(name='test')
print qs.query
For older django versions try:
print str(qs.query)
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.
You also can use python logging to log all queries generated by Django. Just add this to your settings file.
LOGGING = {
'disable_existing_loggers': False,
'version': 1,
'handlers': {
'console': {
# logging handler that outputs log messages to terminal
'class': 'logging.StreamHandler',
'level': 'DEBUG', # message level to be written to console
},
},
'loggers': {
'': {
# this sets root level logger to log debug and higher level
# logs to console. All other loggers inherit settings from
# root level logger.
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False, # this tells logger to send logging message
# to its parent (will send if set to True)
},
'django.db': {
# django also has database level logging
},
},
}
Another method in case application is generating html output - django debug toolbar can be used.
If you are using database routing, you probably have more than one database connection.
Code like this lets you see connections in a session.
You can reset the stats the same way as with a single connection: reset_queries()
from django.db import connections,connection,reset_queries
...
reset_queries() # resets data collection, call whenever it makes sense
...
def query_all():
for c in connections.all():
print(f"Queries per connection: Database: {c.settings_dict['NAME']} {c.queries}")
# and if you just want to count the number of queries
def query_count_all()->int:
return sum(len(c.queries) for c in connections.all() )
You can use a Django debug_toolbar to view the SQL query. Step by step guide for debug_toolbar usage :
pip install django-debug-toolbar
Settings.py=>
INSTALLED_APPS= [ 'debug_toolbar']
MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware']
Settings.py=> create new list at the end of settings.py file & add below list:
INTERNAL_IPS= [127.0.0.1']
This will allow the debug to run only on internal developement server
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls))
] + urlpatterns
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.