Viewing SQL Queries Performed by Django
When executing queries, Django runs SQL commands that are often not visible to developers. However, there are methods to observe these queries and inspect their contents.
Access Query Lists
Django stores a list of all executed queries in django.db.connection.queries. To view these queries:
<code class="python">from django.db import connection print(connection.queries)</code>
Retrieve Query from Querysets
Querysets, representing database queries, have a query attribute that contains the raw SQL to be executed:
<code class="python">print(MyModel.objects.filter(name="my name").query)</code>
Note on Output Limitations
It's important to note that the displayed SQL may not be syntactically valid as:
"Django never actually interpolates the parameters: it sends the query and the parameters separately to the database adapter, which performs the appropriate operations."
This means that the displayed query cannot be directly executed on a database.
Resetting Queries
If you need to reset the query list, for example, to count queries run within a specific period, use reset_queries from django.db:
<code class="python">from django.db import reset_queries from django.db import connection reset_queries() # Run your query here print(connection.queries) >>> []</code>
The above is the detailed content of How Can I View SQL Queries Performed by Django?. For more information, please follow other related articles on the PHP Chinese website!