Django how to see generated SQL query?

I have a form that takes data and needs to insert it into a database. When I process this form it gives me a value error, but when I go to the database and try to insert it manually it works fine.

To debug this situation, I want to see which request Django is generating which is not working. On the debug webpage, I have not seen anything like a SQL query.

How can I see the actual request Django generated?

Please advise. Thank.

+5


source to share


2 answers


How to use the magazine?

you can add this to 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 to 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 the SQL query.

Another way

go shell

python manage.py shell

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

      

you can see the raw request string.

+9


source


If you are using PyCharm, running the application in the debugger gives the full context. Set a breakpoint and find the point in your application where you gave the error and you get a screen (trivial example): enter image description here

Running this way changed the way I troubleshoot when using Django. I suspect other IDEs may have similar functionality. Some additional video documentation of the process from the vendor at: https://www.youtube.com/watch?v=QJtWxm12Eo0



As Jayground suggested, registration is probably what you'll eventually turn on; great offer.

+1


source







All Articles