是否有一种方法可以在执行查询时显示Django正在运行的SQL ?
当前回答
Django SQL Sniffer是查看(和查看)从Django ORM的任何进程中执行的原始查询的另一种选择。我已经构建了它来满足我所拥有的一个特定用例,我在任何地方都没有看到过,即:
不需要更改目标进程正在执行的源代码(不需要在django设置中注册一个新的应用程序,到处导入装饰器等)。 不更改日志配置(例如,因为我对一个特定的进程感兴趣,而不是配置应用的整个进程群) 不需要重新启动目标进程(例如,因为它是一个重要的组件,重新启动可能会导致一些停机时间)
因此,Django SQL Sniffer可以特别使用,并附加到已经运行的进程。然后,该工具“嗅探”已执行的查询,并在执行时将它们打印到控制台。当工具停止时,将显示一个统计摘要,其中包含基于某些可能的度量(计数、最大持续时间和总组合持续时间)的异常值查询。
这是我附加到Python shell的示例的截图
你可以在github页面上查看现场演示和更多细节。
其他回答
下面基于https://code.djangoproject.com/ticket/17741:返回有效的SQL查询
def str_query(qs):
"""
qs.query returns something that isn't valid SQL, this returns the actual
valid SQL that's executed: https://code.djangoproject.com/ticket/17741
"""
cursor = connections[qs.db].cursor()
query, params = qs.query.sql_with_params()
cursor.execute('EXPLAIN ' + query, params)
res = str(cursor.db.ops.last_executed_query(cursor, query, params))
assert res.startswith('EXPLAIN ')
return res[len('EXPLAIN '):]
我为此开发了一个扩展,所以你可以很容易地在你的视图函数上放一个装饰器,看看有多少查询被执行了。
如何安装:
$ 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
我相信这应该工作,如果你使用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())}')
看一下debug_toolbar,它对调试非常有用。
文档和源代码可以在http://django-debug-toolbar.readthedocs.io/上找到。
如果你确保你的settings.py文件有:
django.core.context_processors.debug中列出的 DEBUG = True INTERNAL_IPS元组中的IP
然后您应该可以访问sql_queries变量。我在每个页面上都添加了一个页脚,如下所示:
{%if sql_queries %}
<div class="footNav">
<h2>Queries</h2>
<p>
{{ sql_queries|length }} Quer{{ sql_queries|pluralize:"y,ies" }}, {{sql_time_sum}} Time
{% ifnotequal sql_queries|length 0 %}
(<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.disp\
lay=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>)
{% endifnotequal %}
</p>
<table id="debugQueryTable" style="display: none;">
<col width="1"></col>
<col></col>
<col width="1"></col>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">SQL</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody>
{% for query in sql_queries %}
<tr class="{% cycle odd,even %}">
<td>{{ forloop.counter }}</td>
<td>{{ query.sql|escape }}</td>
<td>{{ query.time }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
通过添加一行,我得到了变量sql_time_sum
context_extras['sql_time_sum'] = sum([float(q['time']) for q in connection.queries])
到django_src/django/core/context_processors.py中的debug函数。
推荐文章
- 什么是数据库池?
- GROUP BY with MAX(DATE)
- 每n秒运行特定代码
- 删除id与其他表不匹配的sql行
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 等价的限制和偏移SQL Server?
- 关于数据库,每个开发人员应该知道些什么?
- 在Python中重置生成器对象
- 用Python构建最小的插件架构
- model.eval()在pytorch中做什么?
- Tensorflow 2.0:模块“Tensorflow”没有属性“Session”
- 从环境文件中读入环境变量
- 在OSX 10.11中安装Scrapy时,“OSError: [Errno 1]操作不允许”(El Capitan)(系统完整性保护)