"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Inspect the SQL Queries Executed by Django?

How Can I Inspect the SQL Queries Executed by Django?

Published on 2024-11-11
Browse:366

How Can I Inspect the SQL Queries Executed by Django?

How to Inspect SQL Queries in Django

Want to know the SQL statements that Django runs when executing a query? The answer is simple:

1. Find the answer from the documentation
The FAQ section of the Django documentation provides a straightforward answer:

2. Access the database Connections
can access the SQL query list through django.db.connection.queries:

from django.db import connection
print(connection.queries)

3. View the Queryset object
The Queryset object has a query attribute that contains the query to be executed:

print(MyModel.objects.filter(name="my name").query)

Note: The query output by is not valid SQL. The reason is:

"Django never actually interpolates parameters: it sends the query and parameters separately to the database adapter, which performs the appropriate operations."

(from Django bug report #17741)

Therefore, do not send query output directly to the database.

Reset queries
If you need to reset a query, such as to see the number of queries run in a given time period, you can use django.db.reset_queries:

from django.db import reset_queries
from django.db import connection

reset_queries()
# 运行你的查询
print(connection.queries)
>>> []
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3