gpt4 book ai didi

django - 当 Debug 为 False 时,如何从 Django 打印 sql 查询

转载 作者:行者123 更新时间:2023-12-04 11:56:38 25 4
gpt4 key购买 nike

来自文档 how can I see the raw SQL queries Django is running?
我可以通过以下方式执行sql:

from django.db import connection
connection.queries
但它仅在 Debug == True 时可用
如何将 sql 打印为 Debug == False ?
谢谢

Update


我想要这样的东西:
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))


最佳答案

您可以与 Database instrumentation [Django docs] 合作它基本上提供了一个钩子(Hook),用于在数据库查询的执行周围安装包装函数。使用它,您可以简单地制作一个包装器,如下所示:

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)
然后在您的 View 中使用它:
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 - 当 Debug 为 False 时,如何从 Django 打印 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67683964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com