Django: show me the sql!

This week, I noticed that there was a select query in our production system without a where clause, and it was running a lot. Tracking it down, I found the piece of code that was running the query, but I couldn't be sure that my fix was actually changing the SQL to what I wanted.

In Django, it's pretty easy to ask the framework for the SQL in question. You can use the Debug toolbar, but in my case, this wasn't something that was running in a view. Instead, I used the interactive shell.

./ shell
from django.db import connection
from myapp.models import MyModel
>[<MyModel: 1>, <MyModel: 2>, <MyModel: 3>, '...(remaining elements truncated)...']
print connection.queries
>[{'time': '0.002', 'sql': 'SELECT "myapp_mymodel"."id", "myapp_mymodel"."field1", "myapp_mymodel"."field1" FROM "myapp_mymodel"'}]

In my case, I was calling .exists() before getting the first element in the result set. Of course, the exists was returning all the items in the database! Instead, I just used a try/catch around MyModel.objects.all()[0].

I'm currently working at NerdWallet, a startup in San Francisco trying to bring clarity to all of life's financial decisions. We're hiring like crazy. Hit me up on Twitter, I would love to talk.

Follow @chase_seibert on Twitter