Python 从 Django QuerySet 获取 SQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3748295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the SQL from a Django QuerySet
提问by exupero
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. Thanks for your help.
如何从 QuerySet 对象获取 Django 将在数据库上使用的 SQL?我正在尝试调试一些奇怪的行为,但我不确定哪些查询会发送到数据库。谢谢你的帮助。
采纳答案by jpwatts
You print the queryset's queryattribute.
您打印查询集的query属性。
>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"
回答by Mike Axiak
Easy:
简单:
print my_queryset.query
For example:
例如:
from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query
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:
还应该提到的是,如果您有 DEBUG = True,那么您的所有查询都会被记录下来,您可以通过访问 connection.queries 来获取它们:
from django.db import connections
connections['default'].queries
The django debug toolbarproject uses this to present the queries on a page in a neat manner.
在Django的调试工具栏项目使用此提出查询页面上在一个整洁的方式。
回答by Guillaume Esquevin
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
这个中间件会将每个 SQL 查询输出到您的控制台,并带有颜色突出显示和执行时间,这对我优化一些棘手的请求非常有用
回答by Tomasz Zieliński
As an alternative to the other answers, django-devserveroutputs SQL to the console.
作为其他答案的替代方案,django-devserver 将SQL 输出到控制台。
回答by Hakan B.
The accepted answerdid 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>.
使用 Django 1.4.4 时,接受的答案对我不起作用。返回了对 Query 对象的引用,而不是原始查询:<django.db.models.sql.query.Query object at 0x10a4acd90>。
The following returned the query:
以下返回查询:
>>> queryset = MyModel.objects.all()
>>> queryset.query.__str__()

