是否有一种方法可以在执行查询时显示Django正在运行的SQL ?
当前回答
在django中,如果你有这样的查询:
MyModel.objects.all()
do:
MyModel.objects.all().query.sql_with_params()
or:
str(MyModel.objects.all().query)
来获取SQL字符串
其他回答
from django.db import reset_queries, connection
class ShowSQL(object):
def __enter__(self):
reset_queries()
return self
def __exit__(self, *args):
for sql in connection.queries:
print('Time: %s\nSQL: %s' % (sql['time'], sql['sql']))
然后你可以使用:
with ShowSQL() as t:
some queries <select>|<annotate>|<update> or other
它打印
时间:% s SQL: % s
我已经做了一个你可以使用的小片段:
from django.conf import settings
from django.db import connection
def sql_echo(method, *args, **kwargs):
settings.DEBUG = True
result = method(*args, **kwargs)
for query in connection.queries:
print(query)
return result
# HOW TO USE EXAMPLE:
#
# result = sql_echo(my_method, 'whatever', show=True)
它以参数函数(包含sql查询)来检查和args, kwargs需要调用该函数。结果它返回函数返回的内容,并在控制台中打印SQL查询。
请参阅文档常见问题:“如何查看Django正在运行的原始SQL查询?”
django.db.connection.queries包含一个SQL查询列表:
from django.db import connection
print(connection.queries)
queryset也有一个包含要执行的查询的query属性:
print(MyModel.objects.filter(name="my name").query)
注意,查询的输出不是有效的SQL,因为:
Django从未真正插入参数:它将查询和参数分别发送到数据库适配器,由数据库适配器执行适当的操作。
来自Django错误报告#17741。
因此,不应该将查询输出直接发送到数据库。
如果你需要重置查询,例如,查看在给定的时间内有多少查询在运行,你可以使用reset_queries from django.db:
from django.db import reset_queries
from django.db import connection
reset_queries()
# Run your query here
print(connection.queries)
>>> []
我相信这应该工作,如果你使用PostgreSQL:
from django.db import connections
from app_name import models
from django.utils import timezone
# Generate a queryset, use your favorite filter, QS objects, and whatnot.
qs=models.ThisDataModel.objects.filter(user='bob',date__lte=timezone.now())
# Get a cursor tied to the default database
cursor=connections['default'].cursor()
# Get the query SQL and parameters to be passed into psycopg2, then pass
# those into mogrify to get the query that would have been sent to the backend
# and print it out. Note F-strings require python 3.6 or later.
print(f'{cursor.mogrify(*qs.query.sql_with_params())}')
虽然可以使用提供的代码来完成,但我发现使用调试工具栏应用程序是显示查询的一个很好的工具。你可以从github下载。
这使您可以选择显示在给定页面上运行的所有查询以及查询所花费的时间。它还汇总了页面上的查询数量以及用于快速查看的总时间。当你想了解Django ORM在幕后做了什么时,这是一个很好的工具。它也有很多其他不错的功能,你可以使用,如果你喜欢。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何在Ruby On Rails中使用NuoDB手动执行SQL命令
- 查询JSON类型内的数组元素
- 如何在django应用程序中显示favicon ?
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 确定记录是否存在的最快方法
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 获得PostgreSQL数据库中当前连接数的正确查询
- 如何创建类属性?