简体   繁体   English

SQLAlchemy中的楼层划分

[英]Floor division in SQLAlchemy

In SQLAlchemy I'd like to divide by a number and then round down. 在SQLAlchemy中,我想除以一个数字然后四舍五入。 Eg I'm looking for the Python equivalent of the following 例如,我正在寻找以下的Python等效项

>>> 3.1415 // 0.1
31.0

Sadly SQLAlchemy Column Elements don't seem to support __floordiv__ 不幸的是,SQLAlchemy列元素似乎不支持__floordiv__

>>> mycol // 3
***TypeError: unsupported operand type(s) for //: 'Column' and 'int'

Is there a way to get around this? 有办法解决这个问题吗? Is there an equivalent to math.floor ? 有相当于math.floor吗?

Keep in mind that performing operations on columns is actually creating an expression that will be executed by the database. 请记住,对列执行操作实际上是在创建一个将由数据库执行的表达式。 There doesn't seem to be a standard way between different databases to "force" integer division. 在不同的数据库之间似乎没有一种“强制”整数除法的标准方法。

The answer is database dependent. 答案取决于数据库。 PostgreSQL has the div function which performs integer division. PostgreSQL具有执行整数除法的div函数。

from sqlalchemy import func

session.query(func.div(mycol, 3)).scalar()

SQLite, on the other hand, has no built-in way to do this, although you could cast the result to an integer if you don't care about correctness for negative values (casting chops off the fractional part, while flooring should always return a number less than the input). 另一方面,SQLite没有内置的方法来执行此操作,尽管如果您不关心负值的正确性(可以将小数部分切掉,而地板应始终返回),则可以将结果转换为整数。小于输入的数字)。

from sqlalchemy import cast, Integer

session.query(cast(mycol / 3, Integer)).scalar()
# -3.14 returns -3, but should return -4

If you want some "general" solution, you could use a case statement, but it's ugly. 如果您需要某种“通用”解决方案,则可以使用case语句,但这很丑陋。

from sqlalchemy import case, cast, Integer

session.query(cast(case([(mycol < 0, mycol - 1)], else_=mycol), Integer)).scalar()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM