views:

1533

answers:

3

Hi folks,

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?

Thanks in advance!

+8  A: 

Each QuerySet object has a 'query' field 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.

Joe Holloway
Thank you for providing me the anwser!
what about queries for .save()?
DataGreed
@DataGreed Good question, might be worth asking in a new thread so you get more responses.
Joe Holloway
+6  A: 

As long as DEBUG is on:

from django.db import connection
print connection.queries

For an individual query, you can do:

Model.objects.filter(name='test').query.as_sql()
Daniel Roseman
Also thanks for learning me about the query.as_sql method :-)
+6  A: 

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.

Mike Korobov