Home > Article > Backend Development > How Do I View the Raw SQL Queries Executed by Django?
Django SQL Query Visibility
To observe the raw SQL queries executed by Django, you can refer to the Django documentation's FAQ for this specific question.
Using django.db.connection.queries
One method is to utilize the django.db.connection.queries attribute, which maintains a list of executed SQL queries. To display them:
<code class="python">from django.db import connection print(connection.queries)</code>
Inspecting Queryset Queries
Querysets also possess a query attribute that contains the query to be executed. To access it:
<code class="python">from django.db import models print(MyModel.objects.filter(name="my name").query)</code>
Important Note
It's crucial to note that the output of the query is not valid SQL. This is because:
"Django never actually interpolates the parameters: it sends the query and the parameters separately to the database adapter, which performs the appropriate operations."
Resetting Queries
If you need to reset the list of executed queries to, for example, assess the number of queries within a specific time frame, employ the reset_queries function from django.db:
<code class="python">from django.db import reset_queries from django.db import connection reset_queries() # Execute your query here print(connection.queries)</code>
The above is the detailed content of How Do I View the Raw SQL Queries Executed by Django?. For more information, please follow other related articles on the PHP Chinese website!