简体   繁体   中英

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 ).

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". Other "firing" methods include all() , first() and so on.

How to get SQL for such methods?

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). Other methods can alter resulting SQL as well, for example, first() .

So, sometimes it is useful to get raw SQL of such queries in order to investigate how thing goes under the hood.

I read answers about "getting raw SQL" but this case is special because such methods don't return Query objects .

Note that I mean that I need a SQL of existing Query objects which are already constructed in some way.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM