How to view corresponding SQL query of the Django ORM's queryset?

DjangoNewbe picture DjangoNewbe · Jun 9, 2009 · Viewed 93.9k times · Source

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?

Answer

Joe Holloway picture Joe Holloway · Jun 9, 2009

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

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.