Explain Codes LogoExplain Codes Logo

How can I see the raw SQL queries Django is running?

python
debugging
sql-optimization
django-orm
Nikita BarsukovbyNikita Barsukov·Nov 16, 2024
TLDR

To peek at Django's raw SQL queries, hit up connection.queries, but make sure DEBUG is set True first.

from django.db import connection # Your query execution here, anxiously waiting to be seen... print(connection.queries) # Get ready to read some SQL poetry!

Note: This being enabled in production might lead to a spectacular, if unintended, fireworks show (a.k.a. performance issues). So, beware!

Deep dive

Peering into Django's crystal ball: .query

Django's ORM QuerySets can foresee your SQL future with the .query attribute, minus actual database hit. Like window shopping... but for SQL:

my_queryset = MyModel.objects.all() print(my_queryset.query) # SQL's future is looking... SELECTive

Debugging made stylish with Django Debug Toolbar

Django Debug Toolbar is your high-tech monocle for SQL inspection. It parades your SQL queries with their runtimes, so you can optimize your code without breaking a sweat!

pip install django-debug-toolbar

Add it to your INSTALLED_APPS and middleware. Off you go, Sherlock!

Monitor, reset, repeat with reset_queries

To avoid takign a detour down memory lane with past queries, reset_queries to wipe the slate clean:

from django.db import reset_queries reset_queries() # Fire off some queries here print(connection.queries) # Who you see here, stay here!

Real-time thrill with database logs

For a real-time broadcast of your database dialogue:

  • Run tail -f on Linux to tail database logs.
  • Watch your app and database have their little SQL chat.

Safety first: avoiding print() in production

Remember the kindergarten rule about not talking to strangers? That applies here. Avoid direct raw SQL output and stick to database adapters to prevent opening doors to unwanted SQL injections!

Welcome aboard the django-extensions express

With shell_plus and print-sql, django-extensions lets you closely watch your ORM's translation into SQL.

python manage.py shell_plus --print-sql

Advanced insights

Decodifying SQL for performance optimization

Gaining insight into the SQL execution process aids you in fine-tuning performance. You'll be the SQL whisperer, eavesdropping into your database's inner monologue to improve its interaction skills.

Exercise caution with direct output

Avoid directly printing queries in production environments—it could turn your logs into a dense jungle with sneaky log leopards lurking about.

Seizing the reins with database-specific commands

Take command and utilize database-specific features like PostgreSQL's pg_stat_statements to orchestrate a perfect ballet of SQL statements.

Reading between the lines for prime performance

Performance lies in the well-timed pause and the skipped beat. Monitoring the execution time and devouring contextual database info bring you closer to running a well-oiled SQL machinery.