简体   繁体   中英

Floor division in SQLAlchemy

In SQLAlchemy I'd like to divide by a number and then round down. Eg I'm looking for the Python equivalent of the following

>>> 3.1415 // 0.1
31.0

Sadly SQLAlchemy Column Elements don't seem to support __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 ?

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.

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).

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.

from sqlalchemy import case, cast, Integer

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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