DEV Community

tomaszd
tomaszd

Posted on

See All Raw SQL queries in django

How to see all RAW SQL queries in django.
There is one nice option to do that.

Server Logs

Change the logging level to DEBUG.
you can add this small snippet in settings.py:


if DEBUG:
    import logging
    l = logging.getLogger('django.db.backends')
    l.setLevel(logging.DEBUG)
    l.addHandler(logging.StreamHandler())

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}
Enter fullscreen mode Exit fullscreen mode

Then inside the views or tests or any other file please add change of debug level:

import logging

l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
Enter fullscreen mode Exit fullscreen mode

or even add that to settings.py to have it globally:


if DEBUG:
    import logging
    l = logging.getLogger('django.db.backends')
    l.setLevel(logging.DEBUG)
    l.addHandler(logging.StreamHandler())

Enter fullscreen mode Exit fullscreen mode

Then observe the logs of your up and running server :

queryRawSql

Queryset query param

python manage.py shell

from model import ExampleModel
queryset = ExampleModel.objects.all()
print(queryset.query)
or
queryset.raw
Enter fullscreen mode Exit fullscreen mode

Discussion (0)