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

Viewed 115249

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?

8 Answers

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.

As long as DEBUG is on:

from django.db import connection
print(connection.queries)

For an individual query, you can do:

print(Model.objects.filter(name='test').query)

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.

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() )
Related