【问题标题】:Getting COUNT from sqlalchemy从 sqlalchemy 获取 COUNT
【发布时间】:2017-11-25 03:59:12
【问题描述】:

我有:

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

一定有更简单的方法吧?它是什么?我还没有发现。 注意:数据库是postgres db。

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

    虽然其他答案有效,但 SQLAlchemy 为标量查询提供了一个快捷方式,如 ResultProxy.scalar()

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

    scalar() 获取第一行的第一列并关闭结果集,如果没有行则返回 None。如果使用查询 API,还有 Query.scalar()

    【讨论】:

      【解决方案2】:

      您要求的称为拆包ResultProxyiterable,所以我们可以这样做

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

      【讨论】:

        【解决方案3】:

        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

        【讨论】:

        • 此语法使用 SQLAlchmy 1.3.20 返回此错误TypeError: 'ResultProxy' object is not subscriptable
        猜你喜欢
        • 1970-01-01
        • 2012-01-06
        • 2013-08-09
        • 1970-01-01
        • 2019-02-14
        • 2011-09-20
        • 2020-11-07
        • 1970-01-01
        • 2014-08-21
        相关资源
        最近更新 更多