I’m working on a Django project and need to debug some performance issues with my database queries. The problem is that I can’t figure out what SQL commands are actually being generated and executed by Django’s ORM when I run my QuerySets.
I’ve been trying to optimize my models and queries, but without seeing the raw SQL output, it’s really hard to tell if my changes are making things better or worse. Sometimes the ORM generates pretty complex joins and subqueries that I didn’t expect.
Does Django provide any built-in tools or methods that would let me inspect the actual SQL statements being sent to the database? I’m looking for something that shows the complete query with all the parameters filled in, not just the template.
The connection.queries
approach gives you direct access to executed SQL statements without needing extra packages. After running your QuerySet operations, just check django.db.connection.queries
to see all executed queries with actual parameters. Works great in development when you’ve got DEBUG=True
in your settings. You can also use the query
attribute on any QuerySet before execution, though that shows the template form instead of the final statement. This technique saved me tons of time when optimizing complex queries with multiple joins - shows exactly how Django converts your ORM calls to SQL without changing your code or installing anything extra.
hey, have you checked out django-debug-toolbar? it’s really useful for debugging! it displays all ur db queries in the browser, which is awesome for seeing what’s runnung. just pip install it and add it to your middleware!
Oh nice! Quick question - can you see queries as they run in real-time? Like something that dumps them to console while the app’s running? Would be perfect for catching those n+1 issues that only show up when you’re actually using the thing.