[英]SQLAlchemy - how to get raw SQL of `.count()` queries?
The simplest possible way to get "raw" SQL for any query is just print
it (actually, convert it to str
). 为任何查询获取“原始”SQL的最简单方法就是
print
它(实际上,将其转换为str
)。
But , this is not working for count()
queries because count()
is "firing" method - a method which is stated as "This results in an execution of the underlying query". 但是 ,这不适用于
count()
查询,因为count()
是“触发”方法 - 一种方法,表示为“这导致执行基础查询”。 Other "firing" methods include all()
, first()
and so on. 其他“触发”方法包括
all()
, first()
等。
How to get SQL for such methods? 如何获取这些方法的SQL?
I'm especially interested in count()
because it transforms underlying query in some way (actually, this way is described explicitly in docs , but things may vary). 我对
count()
特别感兴趣,因为它以某种方式转换底层查询(实际上,这种方式在docs中有明确描述,但事情可能会有所不同)。 Other methods can alter resulting SQL as well, for example, first()
. 其他方法也可以改变生成的SQL,例如
first()
。
So, sometimes it is useful to get raw SQL of such queries in order to investigate how thing goes under the hood. 因此,有时获取此类查询的原始SQL以便调查事情是如何进行的。
I read answers about "getting raw SQL" but this case is special because such methods don't return Query
objects . 我阅读了关于“获取原始SQL”的答案,但这种情况很特殊,因为这些方法不会返回
Query
对象 。
Note that I mean that I need a SQL of existing Query
objects which are already constructed in some way. 请注意,我的意思是我需要一个已经以某种方式构造的现有
Query
对象的SQL。
The following example will return a count of any query object, which you should then be able to convert to a string representation: 以下示例将返回任何查询对象的计数,然后您应该能够将其转换为字符串表示形式:
from sqlalchemy import func
...
existing_query = session.query(Something)\
.join(OtherThing)\
.filter(OtherThing.foo = 'FOO')\
.subquery()
query = session.query(func.count(existing_query.c.bar).label('bar_count'))
print(query)
actual_count = query.as_scalar() # Executes query
Notice that you have to specify a field from the query output to count. 请注意,您必须从查询输出中指定要计数的字段。 In the example defined by
existing_query.c.bar
. 在
existing_query.c.bar
定义的示例中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.