Join my Laravel for REST API's course on Udemy 👀

Get the SQL query from a Django queryset object

March 18, 2021  ‐ 1 min read

The Django ORM abstracts away most of the database stuff. But while debugging or profiling it can be useful to see how Django executes a query.

You can easily get the raw SQL query by accessing the .query property of a queryset object.

>>> users = User.objects.all()
>>> str(users.query)
'SELECT "users_user"."id", "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", "users_user"."first_name", "users_user"."last_name", "users_user"."is_staff", "users_user"."is_active", "users_user"."date_joined", "users_user"."email" FROM "users_user"'

The example above displays this in the Django shell, for a query that gets all the users.