What's the method to view the actual SQL statements executed by Django?

Hey everyone,

I’m working on a Django project and I’m curious about the SQL queries that are being executed behind the scenes. Is there a way to see the actual SQL statements that Django generates when it’s doing database operations?

I’m not looking to modify the queries, just want to understand what’s happening under the hood. It would be super helpful for debugging and optimizing my code.

Any tips or built-in Django features that can help with this? Thanks in advance for your help!

yo, django’s got a built-in way to see those SQL queries. just add ‘django.db.backends’ to ur LOGGING setting in settings.py. it’ll spit out all the SQL stuff to the console. dead simple and works like a charm! :ok_hand:

For viewing SQL statements in Django, I’ve found the ‘connection.queries’ method particularly useful. After executing your database operations, you can access this attribute to see a list of all queries performed during the request. It’s especially helpful when wrapped in a context manager to isolate specific queries.

To implement this, you can use:

from django.db import connection

# Your database operations here
print(connection.queries)

This approach provides detailed insights into the exact SQL being executed, including parameters used. It’s a straightforward way to analyze query performance without additional tools or settings modifications.

Hey there! have you tried using Django Debug Toolbar? it’s pretty nifty for peeking under the hood :mag: it shows SQL queries, execution times, and more. what kinda performance issues are you dealing with? might be fun to dig deeper and see what we can uncover together!