是否有一种方法可以在执行查询时显示Django正在运行的SQL ?
当前回答
在django中,如果你有这样的查询:
MyModel.objects.all()
do:
MyModel.objects.all().query.sql_with_params()
or:
str(MyModel.objects.all().query)
来获取SQL字符串
其他回答
我把这个函数放在我项目中的一个应用程序的util文件中:
import logging
import re
from django.db import connection
logger = logging.getLogger(__name__)
def sql_logger():
logger.debug('TOTAL QUERIES: ' + str(len(connection.queries)))
logger.debug('TOTAL TIME: ' + str(sum([float(q['time']) for q in connection.queries])))
logger.debug('INDIVIDUAL QUERIES:')
for i, query in enumerate(connection.queries):
sql = re.split(r'(SELECT|FROM|WHERE|GROUP BY|ORDER BY|INNER JOIN|LIMIT)', query['sql'])
if not sql[0]: sql = sql[1:]
sql = [(' ' if i % 2 else '') + x for i, x in enumerate(sql)]
logger.debug('\n### {} ({} seconds)\n\n{};\n'.format(i, query['time'], '\n'.join(sql)))
然后,当需要时,我只是导入它,并从任何上下文(通常是视图)调用它是必要的,例如:
# ... other imports
from .utils import sql_logger
class IngredientListApiView(generics.ListAPIView):
# ... class variables and such
# Main function that gets called when view is accessed
def list(self, request, *args, **kwargs):
response = super(IngredientListApiView, self).list(request, *args, **kwargs)
# Call our function
sql_logger()
return response
在模板之外这样做很好,因为如果你有API视图(通常是Django Rest框架),它也适用于模板。
没有其他答案涵盖这个方法,所以:
我发现迄今为止最有用、最简单、最可靠的方法是询问您的数据库。例如,在Linux的Postgres上,你可能会这样做:
sudo su postgres
tail -f /var/log/postgresql/postgresql-8.4-main.log
每个数据库的过程略有不同。在数据库日志中,你不仅可以看到原始SQL,还可以看到django在系统上设置的任何连接或事务开销。
请参阅文档常见问题:“如何查看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)
>>> []
使用django.db.connection.queries查看查询
from django.db import connection
print(connection.queries)
访问QuerySet对象上的原始SQL查询
qs = MyModel.objects.all()
print(qs.query)
我为此开发了一个扩展,所以你可以很容易地在你的视图函数上放一个装饰器,看看有多少查询被执行了。
如何安装:
$ pip install django-print-sql
用作上下文管理器:
from django_print_sql import print_sql
# set `count_only` to `True` will print the number of executed SQL statements only
with print_sql(count_only=False):
# write the code you want to analyze in here,
# e.g. some complex foreign key lookup,
# or analyzing a DRF serializer's performance
for user in User.objects.all()[:10]:
user.groups.first()
装饰:用作装饰:
from django_print_sql import print_sql_decorator
@print_sql_decorator(count_only=False) # this works on class-based views as well
def get(request):
# your view code here
Github: https://github.com/rabbit-aaron/django-print-sql
推荐文章
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- 将值从同一表中的一列复制到另一列
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 什么是数据库池?
- GROUP BY with MAX(DATE)
- 每n秒运行特定代码
- 删除id与其他表不匹配的sql行
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 等价的限制和偏移SQL Server?
- 关于数据库,每个开发人员应该知道些什么?
- 在Python中重置生成器对象