Home > Backend Development > Python Tutorial > How Do I View the Raw SQL Queries Executed by Django?

How Do I View the Raw SQL Queries Executed by Django?

Mary-Kate Olsen
Release: 2024-11-01 21:19:02
Original
798 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template