有没有办法可以打印 Django ORM 正在生成的查询?
假设我执行以下语句:Model.objects.filter(name='test')
如何查看生成的 SQL 查询?
有没有办法可以打印 Django ORM 正在生成的查询?
假设我执行以下语句:Model.objects.filter(name='test')
如何查看生成的 SQL 查询?
每个 QuerySet 对象都有一个query
属性,您可以将其记录或打印到标准输出以进行调试。
qs = Model.objects.filter(name='test')
print(qs.query)
请注意,在 pdb 中, usingp qs.query
不会按预期工作,但print(qs.query)
会。
如果这不起作用,对于旧 Django 版本,请尝试:
print str(qs.query)
编辑
我还使用自定义模板标签(如本片段中所述)将查询注入单个请求范围内作为 HTML 注释。
您还可以使用 python 日志记录 Django 生成的所有查询。只需将其添加到您的设置文件中。
LOGGING = {
'disable_existing_loggers': False,
'version': 1,
'handlers': {
'console': {
# logging handler that outputs log messages to terminal
'class': 'logging.StreamHandler',
'level': 'DEBUG', # message level to be written to console
},
},
'loggers': {
'': {
# this sets root level logger to log debug and higher level
# logs to console. All other loggers inherit settings from
# root level logger.
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False, # this tells logger to send logging message
# to its parent (will send if set to True)
},
'django.db': {
# django also has database level logging
'level': 'DEBUG'
},
},
}
如果应用程序生成 html 输出的另一种方法 -可以使用django 调试工具栏。
您可以将此代码粘贴到您的 shell 上,该 shell 将显示所有 SQL 查询:
# To get all sql queries sent by Django from py shell
import logging
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
只要DEBUG
开启:
from django.db import connection
print(connection.queries)
对于单个查询,您可以执行以下操作:
print(Model.objects.filter(name='test').query)
也许您应该看一下django-debug-toolbar
应用程序,它会为您记录所有查询,为它们显示分析信息等等。
一个强大的解决方案是让您的数据库服务器记录到一个文件,然后
tail -f /path/to/the/log/file.log
如果您使用数据库路由,您可能有多个数据库连接。像这样的代码可以让您查看会话中的连接。您可以像使用单个连接一样重置统计信息:reset_queries()
from django.db import connections,connection,reset_queries
...
reset_queries() # resets data collection, call whenever it makes sense
...
def query_all():
for c in connections.all():
print(f"Queries per connection: Database: {c.settings_dict['NAME']} {c.queries}")
# and if you just want to count the number of queries
def query_count_all()->int:
return sum(len(c.queries) for c in connections.all() )
您可以使用 Django debug_toolbar 查看 SQL 查询。debug_toolbar 使用的分步指南:
pip install django-debug-toolbar
设置.py=>
INSTALLED_APPS= [ 'debug_toolbar']
MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware']
Settings.py=> 在 settings.py 文件末尾创建新列表并添加以下列表:
INTERNAL_IPS= [127.0.0.1']
这将允许调试仅在内部开发服务器上运行
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls))
] + urlpatterns
您将在 127.0.0.1 的网页上看到一个附加组件,如果您单击 SQL Query 复选框,您实际上也可以看到查询的运行时间。