SQLAlchemy 查询引发有关 sqlite 和 Decimal 的不必要警告,如何具体禁用?

SQLAlchemy query raises unnecessary warning about sqlite and Decimal, how to specifically disable?

我正在通过金字塔使用 SQLAlchemy 访问一个简单的 sqlite 数据库。

当我构建越来越复杂的查询时,我收到了这个警告:-

SAWarning:Dialect sqlite+pysqlite 原生支持 Decimal 对象,SQLAlchemy 必须从浮点数转换 - 可能会出现舍入错误和其他问题。请考虑在此平台上将小数存储为字符串或整数以实现无损存储。

我的一个查询是这样做的(释义):-

session.query(subquery.c.a*100.0/(subquery.c.b+subquery.c.c))

这里subquery是子查询的名称,a,b,c是整数。

我没有保存查询结果或 运行 任何提交,这纯粹是数据 extraction/querying,因此当出现上述警告时我感到很惊讶。如何忽略此警告而不完全过滤掉它(以防将来我不小心将 Decimal 数据保存到数据库中)?

可以忽略warnings with warnings.filterwarnings as done here:

import warnings
from sqlalchemy.exc import SAWarning
warnings.filterwarnings('ignore',
 r"^Dialect sqlite\+pysqlite does \*not\* support Decimal objects natively\, "
 "and SQLAlchemy must convert from floating point - rounding errors and other "
 "issues may occur\. Please consider storing Decimal numbers as strings or "
 "integers on this platform for lossless storage\.$",
 SAWarning, r'^sqlalchemy\.sql\.type_api$')

编辑: SQLite 和 SQLAlchemy 使用十进制值的问题已经在 this question, and this answer suggests to create TypeDecorator 中讨论过,它在内部将十进制值存储为文本。

对于在您的查询中除以 100.0,该值似乎已转换为 Decimal by SQLAlchemy. However you can create a literal_column,其中 100.0 作为值:

import sqlalchemy
val100 = sqlalchemy.sql.expression.literal_column("100.0")
session.query(subquery.c.a*val100/(subquery.c.b+subquery.c.c))

使用此解决方案时,它不会向我显示警告。

P.D.: 我使用 SQLAlchemy 版本 1.0.11,和 Python 2.7.11.