从 Django 查询集中获取 SQL
如何从 QuerySet 对象获取 Django 将在数据库上使用的 SQL?我正在尝试调试一些奇怪的行为,但我不确定哪些查询将发送到数据库。
How do I get the SQL that Django will use on the database from a QuerySet object? I'm trying to debug some strange behavior, but I'm not sure what queries are going to the database.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您打印查询集的
query
属性。You print the queryset's
query
attribute.简单:
例如:
还应该提到的是,如果您有 DEBUG = True,那么您的所有查询都会被记录下来,您可以通过访问 connection.queries 来获取它们:
django 调试工具栏 项目使用它以简洁的方式在页面上呈现查询。
Easy:
For example:
It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:
The django debug toolbar project uses this to present the queries on a page in a neat manner.
接受的答案在使用 Django 1.4.4 时对我不起作用。返回对 Query 对象的引用,而不是原始查询:
。返回的查询如下:
The accepted answer did not work for me when using Django 1.4.4. Instead of the raw query, a reference to the Query object was returned:
<django.db.models.sql.query.Query object at 0x10a4acd90>
.The following returned the query:
这个中间件会将每个 SQL 查询输出到您的控制台,并带有颜色突出显示和执行时间,这对于我优化一些棘手的请求来说非常宝贵
http://djangosnippets.org/snippets/290/
This middleware will output every SQL query to your console, with color highlighting and execution time, it's been invaluable for me in optimizing some tricky requests
http://djangosnippets.org/snippets/290/
作为其他答案的替代方案, django-devserver 将 SQL 输出到控制台。
As an alternative to the other answers, django-devserver outputs SQL to the console.