Django’s powerful ORM simplifies database interaction, but in some cases it can be very beneficial to inspect the raw SQL query being executed. This article demonstrates how to retrieve and analyze these SQL statements for debugging and optimization.
To access raw SQL queries generated by Django, there are several ways:
django.db.connection.queries: Contains a list of SQL queries executed by the current database connection:
<code class="language-python"> from django.db import connection print(connection.queries)</code>
Querysets: Each Queryset has a query attribute that stores the SQL query it will execute:
<code class="language-python"> print(MyModel.objects.filter(name="my name").query)</code>
Note: Django’s query output is not valid SQL. The database adapter inserts parameters individually, preventing direct execution without proper validation.
To reset the list of queries tracked by Django, use the reset_queries function:
<code class="language-python">from django.db import reset_queries from django.db import connection reset_queries() # 在此处运行您的查询 print(connection.queries) >>> []</code>
The above is the detailed content of How Can I View and Manage Raw SQL Queries in Django?. For more information, please follow other related articles on the PHP Chinese website!