How to View Raw SQL Queries Executed by Django
Last Updated :
22 Aug, 2024
The most important thing while working on Django is to understanding the executed SQL queries running in the background. It is really important from the perspective that, with the help of these SQL queries, one can tune the performance of the database, find the bottlenecks, and troubleshoot the problems appropriately. The three major approaches to viewing raw SQL queries that Django runs will continue.
How to View Raw SQL Queries Executed by Django
1. Django Debug Toolbar
The Django Debug Toolbar is a popular third-party package that provides a rich debugging toolbar for Django projects. Among other features, this one is enabled for displaying the SQL queries performed by Django.
We follow these steps to apply the Django Debug Toolbar
Step 1: We install the Django Debug Toolbar for our project:
python -m pip install django-debug-toolbar
Step 2: We add 'debug_toolbar' to our 'INSTALLED_APPS' setting in 'settings.py'
INSTALLED_APPS = [
# ...
"debug_toolbar",
# ...
]
Step 3: We need to add some urls for debug toolbar to work in the main url file.
project/urls.py
Python
from django.urls import include, path
from debug_toolbar.toolbar import debug_toolbar_urls
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + debug_toolbar_urls()
Step 4: Add the debug tool base to middleware
The most of the operation are done in middlware itself, so we need to add debug toolbar middle ware in the settings.py file
settings.py
Python
MIDDLEWARE = [
# ...
"debug_toolbar.middleware.DebugToolbarMiddleware",
# ...
]
We can place the middleware at the top of all middleware. However, it must come after any other middleware that encodes the response’s content, such as GZipMiddleware.
Step 5: Updated INTERNAL_IPS
INTERNAL_IPS is a list containing IP addresses. Debug toobar will be shown for all the IP addresses mentioned in the INTERNAL_IPS list. We only want to use this feature during development phase, so, we can add "localhost" and "127.0.0.1" to INTERNAL_IPS.
INTERNAL_IPS = [
"localhost",
"127.0.0.1",
# ...
]
Now, we are all done with the configuration and can view the debug toolbar console at all endpoints.
Step 6: Create a model, view and run the server
For a basic view to the toolbar console, we have created a simple Book model and a book list view.
test_app/models.py
Python
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
def __str__(self) -> str:
return self.title
test_app/views.py
Python
from django.shortcuts import render
def book_list(request):
books = Book.objects.all()
return render(request, 'test_app/book_list.html', {'books': books})
test_app/template/test_app/book_list.html
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Debug ToolBar Guide</title>
</head>
<body>
<h1>Book List</h1>
<ul>
{% for book in books %}
<li>
<strong>
{{ book.title }}
</strong>
<small>
({{ book.published_date }})
</small>
</li>
{% endfor %}
</ul>
</body>
</html>
Run the development server:
python manage.py runserver
Output:
Book ListIn the toolbar, select "SQL" to reveal the SQL queries executed.
You can See the Raw SQL Queries Django in Debug Toolbar
In our view, we are executing only one SQL query that is perfectly recorded by the debug toolbar.
Debug toolbar2. Using the 'query' Attribute of QuerySet
Yet another way to view raw SQL queries is to use the query attribute of a QuerySet object. The following method comes in handy when we want to inspect the SQL query generated by a specific QuerySet.
Python
from django.db.models import Q
qs = User.objects.filter(Q(first_name='John') | Q(last_name='Doe'))
print(qs.query)
Output:
SELECT * FROM myapp_mymodel WHERE name = 'John' OR email = '[email protected]'
This will return the raw SQL generated from a QuerySet.
3. Using connection.queries
Django provides an interface to access the executed SQL through the attribute connection.queries. This technique is pretty handy if we want to inspect all of the SQL queries executed by Django.
Python
from django.db import connection
# Execute some queries
User.objects.all()
Book.objects.filter(title='Django')
# Print the executed queries
print(connection.queries)
Output:
[
{'sql': 'SELECT * FROM myapp_mymodel WHERE id = 1', 'time': '0.0003'},
{'sql': 'SELECT * FROM myapp_mymodel WHERE name = \'John\'', 'time': '0.0005'},
{'sql': 'INSERT INTO myapp_mymodel (name, email) VALUES (\'Jane\', \'[email protected]\')', 'time': '0.0012'}
]
This will print a list of dictionaries, each dictionary containing the executed SQL query and its execution time.
Conclusion
In this article, we have demonstrated three different ways to see the raw SQL queries which Django is running. We can use Django Debug Toolbar, the query attribute of the QuerySet, or connection.queries to know the SQL queries being executed by Django and really fine-tune the performance of your database.
Similar Reads
Raw SQL queries in Django views
Let's create a simple Django project that demonstrates the use of raw SQL queries in a view. In this example, we'll create a project to manage a list of books stored in a database. We'll create a view that retrieves books from the database using a raw SQL query and displays them on a webpage. Settin
4 min read
How to Execute SQL queries from CGI scripts
In this article, we will explore the process of executing SQL queries from CGI scripts. To achieve this, we have developed a CGI script that involves importing the database we created. The focus of this discussion will be on writing code to execute SQL queries in Python CGI scripts. The initial step
5 min read
How to log all sql queries in Django?
Django, a popular web framework for Python, simplifies the development of database-driven applications. When building Django applications, it's crucial to monitor and optimize the SQL queries executed by your application for performance and debugging purposes. One effective way to achieve this is by
4 min read
Extracting SQL Queries from Django QuerySets
Django, a high-level Python web framework, simplifies the development of secure and maintainable websites. One of its powerful features is the Object-Relational Mapping (ORM) system, which allows developers to interact with the database using Python code instead of raw SQL. However, there are times
3 min read
How to Execute Raw SQL in SQLAlchemy
In this article, we will see how to write a Conventional SQL query in SQLAlchemy using text() against a PostgreSQL database in python. Creating table for demonstration Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() func
3 min read
How to get GET request values in Django?
Django, a high-level Python web framework, simplifies the process of web development. One common task in web applications is handling GET requests, which are typically used to retrieve data from a server. In this article, we'll create a small Django project that displays a message using data from a
2 min read
How to integrate Mysql database with Django?
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database â SQLlite3, etc. Installation Let's first un
2 min read
How to Do SELECT MAX in Django?
When working with databases in Django, we often need to find the highest value of a specific field in a model. Let's say, find the book with the highest price, the product with the highest discount, etc. This is like doing a SELECT MAX query in SQL. In this article, we'll learn how to find the max v
4 min read
How to Execute Raw SQL in Flask - SQLAlchemy App
In a Flask application that uses SQLAlchemy, we usually interact with the database using Python objects and methods. However, there are times when we need to execute raw SQL queries directlyâfor example, to optimize performance, run complex queries, or perform database-specific operations. This guid
5 min read
How to Query as GROUP BY in Django?
In Django, the powerful ORM (Object-Relational Mapping) allows developers to interact with databases using Python code. One common database operation is the GROUP BY query, which groups rows sharing a property so that aggregate functions can be applied to each group. This article will guide you thro
3 min read