2017-06-22 18 views
3

獲得COUNT我:從SQLAlchemy的

res = db.engine.execute('select count(id) from sometable') 

返回的對象是sqlalchemy.engine.result.ResultProxy

如何從res獲得計數值?

RES不被索引訪問,但我已經想通了這一點爲:

count=None 
for i in res: 
    count = res[0] 
    break 

必須有正確的更簡單的方法?它是什麼?我還沒有發現它。 注意:db是一個postgres db。

回答

4

雖然其他答案工作,SQLAlchemy的爲標量的快捷方式查詢作爲ResultProxy.scalar()

count = db.engine.execute('select count(id) from sometable').scalar() 

scalar()讀取第一行的第一列和關閉結果集,或者如果沒有行存在返回無。如果使用查詢API,還有Query.scalar()

3

你問一個名爲拆包ResultProxy是一個iterable,所以我們可以做

# there will be single record 
record, = db.engine.execute('select count(id) from sometable') 
# this record consist of single value 
count, = record 
2

在SQLAlchemy中的ResultProxy(這裏http://docs.sqlalchemy.org/en/latest/core/connections.html?highlight=execute#sqlalchemy.engine.ResultProxy文檔)是列從數據庫返回的迭代。對於count()查詢,只需訪問第一個元素以獲取該列,然後訪問另一個索引以獲取該列的第一個元素(且僅限於)該元素。

result = db.engine.execute('select count(id) from sometable') 
count = result[0][0] 

如果你碰巧使用的SQLAlchemy的ORM,我會如建議使用在適當的模型Query.count()方法在這裏:http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=count#sqlalchemy.orm.query.Query.count