Logging raw SQL to the console in Django

When working on a Django project it can be useful to see the raw SQL queries being made to your database - you can quickly and easily identify when there are too many calls being made and look for other inefficient access patterns (queries asking for too much data, etc.). Of course, turning on logging at the database is the most useful and what you ultimately want in production - but for development, sometimes it's more convenient to just see the raw SQL queries directly in your Django output console (and also, if you're using SQLite, it doesn't come with any built in query logging capability). Here's how to setup Django SQL logging.

Add the following to your Django settings file (settings.py):

LOGGING = {
    'version': 1,
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'django.db.backends': {
            'level': 'DEBUG',
            'handlers': ['console'],
        }
    }
}

This will log all SQL queries to console when DEBUG is True (during development).

As an example, here's a typical looking query logged to the console:

(0.000) SELECT "catalog_author"."id", "catalog_author"."first_name", "catalog_author"."last_name", "catalog_author"."date_of_birth", "catalog_author"."date_of_death" FROM "catalog_author" WHERE "catalog_author"."id" = 1 LIMIT 21; args=(1,)