How to view corresponding SQL query of the Django ORM's queryset?
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)
Note that in pdb, using p qs.query
will not work as desired, but print(qs.query)
will.
If that doesn't work, for old 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.
You can paste this code on your shell which will display all the SQL queries:
# To get all sql queries sent by Django from py shellimport loggingl = logging.getLogger('django.db.backends')l.setLevel(logging.DEBUG)l.addHandler(logging.StreamHandler())