我设法在两层上使用SQLAlchemy呈现以下SELECt。
SELECT count(*) AS count_1FROM "table"
SQL表达式层的用法
from sqlalchemy import select, func, Integer, Table, Column, metaDatametadata = metaData()table = Table("table", metadata, Column('primary_key', Integer), Column('other_column', Integer) # just to illustrate )print select([func.count()]).select_from(table)来自ORM层的用法
您只需将其子类化
Query(无论如何,您都可以)并提供一种专门的
count()方法,就像这样。
from sqlalchemy import funcclass baseQuery(Query): def count_star(self): count_query = (self.statement.with_only_columns([func.count()]) .order_by(None)) return self.session.execute(count_query).scalar()
请注意,
order_by(None)重置查询的顺序,这与计数无关。
使用此方法,您可以
count(*)在任何ORM查询上使用,这将满足所有已指定的
filter和
join条件。



