python - SQLAlchemy 将 bool 列转换为 int

标签 python postgresql sqlalchemy

我有一个用户记录表,我希望在满足某些条件时查看平均值。条件列是一个 bool 值。 在 Postgresql 中,我可以轻松地转换它:

select id, avg(cond::INT) from table group by id;

但是在 SQLAlchemy 中我找不到任何等同于 ::INT 的东西。
我如何处理类型转换? 我有

orm_query(Table.id, func.avg(Table.cond))

当然会返回错误。

最佳答案

<expr>::<type>Postgresql specific syntax , CAST(<expr> AS <type>)标准 SQL 等价物。在 SQLAlchemy 中,您可以使用多种方式生成类型转换表达式。在这种情况下,您可以简单地:

orm_query(Table.id, func.avg(Table.cond.cast(Integer)))

另一种选择是使用 cast() 构造。

关于python - SQLAlchemy 将 bool 列转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48519633/

相关文章:

python - L-Systems 和 Maya 中的堆栈

python - Pandas 不掉列

python - Flask-Migrate 模型中的枚举类有问题

python - 对列表中的 Python 字典对象进行排序

python - 如何在Python中读取解释后的数据字符串?

postgresql - 根据单独的时区列转换 UTC - Postgres

python - 英雄库/Django : No module named dj_database_url

SQL - 使用 select 使用先前的非空值更新列的空值

python - Sqlalchemy 选择条件

python - SQLAlchemy 会清理原始 SQL 吗?