如何从 Django 打印 sql 查询,因为 Debug 是 False
Posted
技术标签:
【中文标题】如何从 Django 打印 sql 查询,因为 Debug 是 False【英文标题】:How to print sql query from Django as Debug is False 【发布时间】:2021-08-13 11:03:44 【问题描述】:来自文档how can I see the raw SQL queries Django is running?
我可以通过以下方式执行 sql:
from django.db import connection
connection.queries
但它只在Debug == True
时可用
如何将sql打印为Debug == False
?
谢谢
更新
我想要这样的东西:
from django.db import connection
from django.db import reset_queries
reset_queries() # Clears the query.
with transaction.atomic():
r = Amodel.objects.create(
...
)
Bmodel.objects.filter(id__in=handle_ids_).update(status=4)
# Prints the sql executed in this transaction block.
logger.info("[sql_execute]: ".format(connection.queries))
【问题讨论】:
您想查看所有查询还是只查看特定查询? @SergeyPugach 谢谢,我已经更新了我上面的问题 这能回答你的问题吗? How can I see the raw SQL queries Django is running? 【参考方案1】:您可以使用Database instrumentation [Django docs],它基本上提供了一个挂钩,用于安装围绕执行数据库查询的包装函数。使用它,您可以像这样简单地制作一个包装器:
class QueryLogger:
def __init__(self):
self.queries = []
self.errored = False
def __call__(self, execute, sql, params, many, context):
current_query = 'sql': sql, 'params': params, 'many': many
try:
result = execute(sql, params, many, context)
except Exception as e:
self.errored = True
current_query['status'] = 'error'
current_query['exception'] = e
raise
else:
current_query['status'] = 'ok'
return result
finally:
self.queries.append(current_query)
然后在你的视图中使用它:
from django.db import connection
ql = QueryLogger()
with connection.execute_wrapper(ql), transaction.atomic():
r = Amodel.objects.create(
...
)
Bmodel.objects.filter(id__in=handle_ids_).update(status=4)
if not ql.errored:
for query in ql.queries:
print(query)
else:
print("Some error occured")
【讨论】:
以上是关于如何从 Django 打印 sql 查询,因为 Debug 是 False的主要内容,如果未能解决你的问题,请参考以下文章