[Django]-How to exhaustively see queries Django is running?

1๐Ÿ‘

โœ…

You can try changing LOGGING config, for example in your settings.py (logs all your queries if you DEBUG is True):

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'],
        }
    }
}
๐Ÿ‘คAndrey Bondar

1๐Ÿ‘

Yes, You should use the django-debug-toolbar for that. It will display each query made on some view, if that code you want is like, inside some Model or other python file and sometime is called for some view. Even if it is as a signal on model, for instance. It will be caught by the debug-toolbar.

Another option is tu use the python manage.py shell to call those queries. You can use the django-extensions with the --print-sql parameter in order to display it.

Or, print the sql it self, I usally do this:

>>> qs = User.objects.filter(username='luan')
>>> print(qs.query)
SELECT "users_user"."id", "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", "users_user"."username", "users_user"."first_name", "users_user"."last_name", "users_user"."email", "users_user"."is_staff", "users_user"."is_active", "users_user"."date_joined", "users_user"."ref_id", "users_user"."created_on", "users_user"."updated_on" FROM "users_user" WHERE "users_user"."username" = luan ORDER BY "users_user"."id" ASC
๐Ÿ‘คLuan Fonseca

Leave a comment