Jon*_*han 8 sql django django-queryset
您可以按如下方式打印查询集的SQL:
print str(queryset.query)
Run Code Online (Sandbox Code Playgroud)
但是,出于某种原因,这会删除引号,因此您得到:
SELECT `tableA`.`fieldA` FROM `fieldA` WHERE `tableA`.`fieldB` = Foo
Run Code Online (Sandbox Code Playgroud)
代替:
SELECT `tableA`.`fieldA` FROM `fieldA` WHERE `tableA`.`fieldB` = "Foo"
Run Code Online (Sandbox Code Playgroud)
注意到失踪 ""
如何纠正?
如果底层数据库是PostgreSQL,你可以这样做:
from django.db import connection
sql, params = queryset.query.sql_with_params()
cursor = connection.cursor()
cursor.mogrify(sql, params)
Run Code Online (Sandbox Code Playgroud)
sql_with_params 返回没有替换任何值的普通查询以及将在查询中插入的参数.
仍然不建议将其.mogrify()用于除调试之外的其他目的,因为该方法将来可能会消失.
如果要执行查询,可以/应该使用.raw().
YourModel.objects.raw(sql, params)
Run Code Online (Sandbox Code Playgroud)
不完全是你想要的,但如果你有DEBUG = True你可以使用
from django.db import connection
connection.queries
Run Code Online (Sandbox Code Playgroud)
更新:
看Queryset __str__方法:
__str__(self)
| Returns the query as a string of SQL with the parameter values
| substituted in.
|
| Parameter values won't necessarily be quoted correctly, since that is
| done by the database interface at execution time.
Run Code Online (Sandbox Code Playgroud)