| https://docs.djangoproject.com/en/5.0/topics/db/sql/ : > Django gives you two ways of performing raw SQL queries: you can use `Manager.raw()` to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly. https://stackoverflow.com/questions/1074212/how-can-i-see-th... has : MyModel.objects.all().query.sql_with_params()
str(MyModel.objects.all().query)
And: from django.db import connection
from myapp.models import SomeModel
queryset = SomeModel.objects.filter(foo='bar')
sql_query, params = queryset.query.as_sql(None, connection)
with connection.connection.cursor(cursor_factory=DictCursor) as cursor:
cursor.execute(sql_query, params)
data = cursor.fetchall()
But that's still not backend-specific SQL?There should be an interface method for this. Why does psycopg call it mogrify? https://django-debug-toolbar.readthedocs.io/en/latest/panels... : > debug_toolbar.panels.sql.SQLPanel: SQL queries including time to execute and links to EXPLAIN each query But debug toolbars mostly don't work with APIs. https://github.com/django-query-profiler/django-query-profil... : > Django query profiler - one profiler to rule them all. Shows queries, detects N+1 and gives recommendations on how to resolve them https://github.com/jazzband/django-silk : > Silk is a live profiling and inspection tool for the Django framework. Silk intercepts and stores HTTP requests and database queries before presenting them in a user interface for further inspection |
debug_toolbar and silk are both tools that show you what queries were executed by your running application. They're both good tools, but neither quite solves the problem of giving you the executable SQL for a specific queryset (e.g., in a repl).