Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the SQL from a Django QuerySet [duplicate]

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.

like image 257
exupero Avatar asked Sep 20 '10 02:09

exupero


People also ask

How do I get SQL query in Django?

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.

How do you get raw SQL query from Django?

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.


1 Answers

You print the queryset's query attribute.

>>> queryset = MyModel.objects.all() >>> print(queryset.query) SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel" 
like image 119
jpwatts Avatar answered Sep 20 '22 14:09

jpwatts