Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to see generated SQL query?

Tags:

python

django

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 insert it manually it works fine.

In order to debug this situation, I want to see what query Django is generating which is failing. On the debug webpage I didn't see anything like SQL query.

How can I see the actual query generated by Django?

Please advise. Thanks.

like image 904
learner Avatar asked Dec 30 '16 01:12

learner


1 Answers

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

import logging

l = 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.

like image 186
Jayground Avatar answered Sep 22 '22 05:09

Jayground