I have:
res = db.engine.execute('select count(id) from sometable')
The returned object is sqlalchemy.engine.result.ResultProxy
.
How do I get count value from res
?
Res is not accessed by index but I have figured this out as:
count=None
for i in res:
count = res[0]
break
There must be an easier way right? What is it? I didn't discover it yet.
Note: The db is a postgres
db.
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()
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.