Django如何查看生成的SQL查询? [英] 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 insert it manually it works fine.
为了调试这种情况,我想看看Django正在生成哪个查询而失败了。在调试网页上,我没有看到类似SQL查询的内容。
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.
我如何查看Django生成的实际查询?
How can I see the actual query generated by Django?
请告知。
谢谢。
Please advise. Thanks.
推荐答案
如何使用日志记录?
您可以在settings.py中添加它。py
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,
},
},
}
,您可以在任何视图中添加它。py
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())
在控制台中,您可以检查SQL查询。
In your console, you can check SQL query.
去壳
python manage.py shell
>>from yourmodel import Example
>>queryset = Example.objects.all()
>>print(queryset.query)
您可以看到原始查询字符串。
you can see raw query string.
这篇关于Django如何查看生成的SQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!