是否有一种方法可以在执行查询时显示Django正在运行的SQL ?
当前回答
如果你确保你的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函数。
其他回答
请参阅文档常见问题:“如何查看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)
>>> []
虽然可以使用提供的代码来完成,但我发现使用调试工具栏应用程序是显示查询的一个很好的工具。你可以从github下载。
这使您可以选择显示在给定页面上运行的所有查询以及查询所花费的时间。它还汇总了页面上的查询数量以及用于快速查看的总时间。当你想了解Django ORM在幕后做了什么时,这是一个很好的工具。它也有很多其他不错的功能,你可以使用,如果你喜欢。
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
这里已经有几个很好的答案了。
还有一种方法。
在测试中,这样做:
with self.assertNumQueries(3):
response = self.client.post(reverse('payments:pay_list'))
# or whatever
如果查询数量错误,则测试失败,并在控制台中打印所有原始SQL查询。
此外,此类测试有助于控制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框架),它也适用于模板。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- 将值从同一表中的一列复制到另一列
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 什么是数据库池?
- GROUP BY with MAX(DATE)
- 每n秒运行特定代码
- 删除id与其他表不匹配的sql行