#database #django #python #sql

When you are debugging an app using Django, it's sometimes really useful to see the raw SQL queries your app is executing. It helps you in understanding how the SQL queries are built by Django and it also helps you to pinpoint performance problems and optimize the queries.

You can enable the logging by adding the following snippet to your apps settings.py file:

mysite/settings.py

 1LOGGING = {
 2    'version': 1,
 3    'filters': {
 4        'require_debug_true': {
 5            '()': 'django.utils.log.RequireDebugTrue',
 6        }
 7     },
 8     'handlers': {
 9        'console': {
10            'level': 'DEBUG',
11            'filters': ['require_debug_true'],
12            'class': 'logging.StreamHandler',
13         }
14    },
15    'loggers': {
16        'django.db.backends': {
17            'level': 'DEBUG',
18            'handlers': ['console'],
19        }
20    }
21}

When you then run your app, you will see each SQL query as it's executed in the output of e.g. the runserver command:

 1$ ./manage.py runserver
 2Watching for file changes with StatReloader
 3Performing system checks...
 4
 5System check identified no issues (0 silenced).
 6(0.020) SELECT @@SQL_AUTO_IS_NULL; args=None
 7(0.029) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
 8(0.018) SHOW FULL TABLES; args=None
 9(0.018) SELECT `django_migrations`.`id`, `django_migrations`.`app`, `django_migrations`.`name`, `django_migrations`.`applied` FROM `django_migrations`; args=()
10November 05, 2020 - 17:31:19
11Django version 3.1.3, using settings 'mysite.settings'
12Starting development server at http://0.0.0.0:8000/
13Quit the server with CONTROL-C.

To avoid that you accidently enable this in production, I generally add an extra if-statement around this in the settings.py file so that it only runs when a specific environment variable is set (in my setup, it's called DEBUG_SQL):

1if os.environ.get('DEBUG_SQL', '0') == '1':
2    LOGGING = {
3        ...
4    }

More info can be found in the Django documentation.