从 sqlalchemy 获取 COUNT [英] Getting COUNT from sqlalchemy
问题描述
我有:
res = db.engine.execute('select count(id) from sometable')
返回的对象是sqlalchemy.engine.result.ResultProxy
.
如何从 res
获取计数值?
How do I get count value from res
?
Res 不是通过索引访问的,但我认为这是:
Res is not accessed by index but I have figured this out as:
count=None
for i in res:
count = res[0]
break
一定有更简单的方法吧?它是什么?我还没有发现.注意:db 是一个 postgres
db.
There must be an easier way right? What is it? I didn't discover it yet.
Note: The db is a postgres
db.
推荐答案
虽然其他答案有效,但 SQLAlchemy 为标量查询提供了一个快捷方式,如 ResultProxy.scalar()
:
While the other answers work, SQLAlchemy provides a shortcut for scalar queries as ResultProxy.scalar()
:
count = db.engine.execute('select count(id) from sometable').scalar()
scalar()
获取第一行的第一列并关闭结果集,如果没有行则返回 None.还有 Query.scalar()
,如果使用查询 API.
scalar()
fetches the first column of the first row and closes the result set, or returns None if no row is present. There's also Query.scalar()
, if using the Query API.
这篇关于从 sqlalchemy 获取 COUNT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!