Skip to content Skip to sidebar Skip to footer

Django How To See Generated Sql Query?

I have a form which takes data and is supposed to insert it into a database. When I am processing that form it gives me a value error, but when I go to the database and try to inse

Solution 1:

How about using logging?

you can add this in settings.py

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

and you can add this in your any views.py

importloggingl= logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())

In your console, you can check SQL query.

Another way

go shell

python manage.py shell

>>from yourmodel import Example
>>queryset = Example.objects.all()
>>print(queryset.query)

you can see raw query string.

Solution 2:

If you happen to use PyCharm, running your application in the debugger gives you the full context. Set a breakpoint, and browse in your app to the point you are having the error and get a screen like (trivial example): enter image description here

Running in this way has changed the way I troubleshoot when using Django. I suspect other IDE's may have similar features. Some further video documentation of the process from the vendor at: https://www.youtube.com/watch?v=QJtWxm12Eo0

As Jayground suggested, logging is probably something you'll turn on eventually anyway; great suggestion.

Solution 3:

According to django docs

connection.queries includes all SQL statements – INSERTs, UPDATES, SELECTs, etc. Each time your app hits the database, the query will be recorded.

So you can access these queries by running

from django.db import connection
print(connection.queries)

Post a Comment for "Django How To See Generated Sql Query?"