How do I get the SQL that Django will use on the database from a QuerySet object? I'm trying to debug some strange behavior, but I'm not sure what queries are going to the database.
The django debug toolbar project uses this to present the queries on a page in a neat manner. There is no way to get actual SQL without executing the query first, final SQL is generated by the surrounding RDBMS driver, not Django. The answer is correct as it's the most you can get with Django QuerySet.
Executing custom SQL directly The object django.db.connection represents the default database connection. To use the database connection, call connection.cursor() to get a cursor object. Then, call cursor.execute(sql, [params]) to execute the SQL and cursor.fetchone() or cursor.fetchall() to return the resulting rows.
You print the queryset's query
attribute.
>>> queryset = MyModel.objects.all() >>> print(queryset.query) SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With