"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 View SQL Queries Performed by Django?

How Can I View SQL Queries Performed by Django?

Published on 2025-02-04
Browse:465

How Can I View SQL Queries Performed by Django?

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:

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

Retrieve Query from Querysets

Querysets, representing database queries, have a query attribute that contains the raw SQL to be executed:

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

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:

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

reset_queries()
# Run your query here
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