是否有一种方法可以在执行查询时显示Django正在运行的SQL ?
当前回答
虽然可以使用提供的代码来完成,但我发现使用调试工具栏应用程序是显示查询的一个很好的工具。你可以从github下载。
这使您可以选择显示在给定页面上运行的所有查询以及查询所花费的时间。它还汇总了页面上的查询数量以及用于快速查看的总时间。当你想了解Django ORM在幕后做了什么时,这是一个很好的工具。它也有很多其他不错的功能,你可以使用,如果你喜欢。
其他回答
我把这个函数放在我项目中的一个应用程序的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框架),它也适用于模板。
这里已经有几个很好的答案了。
还有一种方法。
在测试中,这样做:
with self.assertNumQueries(3):
response = self.client.post(reverse('payments:pay_list'))
# or whatever
如果查询数量错误,则测试失败,并在控制台中打印所有原始SQL查询。
此外,此类测试有助于控制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函数。
我相信这应该工作,如果你使用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())}')
另一个选项,请参阅本文中描述的settings.py中的日志记录选项
http://dabapps.com/blog/logging-sql-queries-django-13/
Debug_toolbar会降低开发服务器上每个页面的加载速度,而日志记录则不会,因此速度更快。输出可以转储到控制台或文件,所以UI不是很好。但是对于包含大量sql的视图,通过debug_toolbar调试和优化sql可能需要很长时间,因为每个页面加载都非常慢。
推荐文章
- 获取对象的Django管理url
- 比较两个SQL Server数据库(模式和数据)的最佳工具是什么?
- 在SQL中,如何在范围中“分组”?
- 选项(RECOMPILE)总是更快;为什么?
- 如何制作好的可复制的熊猫例子
- 2个数字表的余弦相似度
- 如何从熊猫的两列形成元组列
- 如何读一个文本文件到一个列表或数组与Python
- 设置数据库从单用户模式到多用户
- Django可选url参数
- 在matplotlib上为散点图中的每个系列设置不同的颜色
- oracle中的RANK()和DENSE_RANK()函数有什么区别?
- 如何加载一个tsv文件到熊猫数据框架?
- 从csv文件创建字典?
- 我如何提高一个响应禁止在django