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.

Leave a Comment