3 ways to generate raw SQL queries for your django queries
Django ORM makes querying the database easier.But how to know what is happening behind the scenes or what SQL query is executed for certain django query.Here are some ways that might be useful to know that.
1. Using queryset’s query
attribute
It is the simplest way of finding raw SQL query in django.
>>>queryset = Organization.objects.all()
>>>print(queryset.query) Output:
SELECT "app_organization"."id", "app_organization"."name", "app_organization"."created","app_organization"."updated"" FROM "app_organization">>>str(queryset.query)
Output:
'SELECT "app_organization"."id", "app_organization"."name", "app_organization"."created", "app_organization"."updated" FROM "app_organization"'
2.Django connection
This approach is more informative than the previous one because we can find the raw SQL statement as well as time needed to execute that statement( in seconds).
Make sure DEBUG = True in your settings file for this .
>>>from django.db import connection,reset_queries>>>Organization.objects.all()
>>>connection.queriesOutput:
[{'sql': 'SELECT "app_organization"."id", "app_organization"."name", "app_organization"."created", "app_organization"."updated" FROM "app_organization" LIMIT 21','time': '0.001'}]>>>reset_queries()
Output:
[]
Note: reset_queries() can be used to clear the query list manually at any point.
3.Django Debug Toolbar
The Django Debug Toolbar is a configurable set of panels that display various debug information about the current request/response and when clicked, display more details about the panel’s content including all the SQL queries.
To setup this toolbar in your django project,
pip install django-debug-toolbar
Set DEBUG = True in your settings.
Add 'debug_toolbar'
to your INSTALLED_APPS
settings.
INSTALLED_APPS = [
'debug_toolbar',
]
Add the Debug Toolbar’s URLs to your project’s URLconf.
import debug_toolbar
from django.conf import settings
from django.urls import include, pathurlpatterns = [
...
path('__debug__/', include(debug_toolbar.urls)),
]
The Debug Toolbar is mostly implemented in a middleware.It should be placed as early as possible in the list. Enable it in your settings module as follows:
MIDDLEWARE = [
# ...
'debug_toolbar.middleware.DebugToolbarMiddleware',
# ...
]
The Debug Toolbar is shown only if your IP address is listed in the INTERNAL_IPS
setting.For example: for local development, you must add '127.0.0.1'
to INTERNAL_IPS.
INTERNAL_IPS = [
# ...
'127.0.0.1',
# ...
]