使用 SQLAlchemy 取值的对数 - Flask/SQLAlchemy

Taking logarithm of value using SQLAlchemy - Flask/SQLAlchemy

我正在尝试将 Userscore 属性更新为现有 score 的对数。但是,我不明白如何将数学函数绑定到 sqlalchemy.sql.func

例如:

import math
from sqlalchemy.sql import func


def mul_2(user):
    return user.score * 2

def _log(user):
    return func.math.log(user.score)


# This works fine
User.query.update({User.score: mul_2(User)})

# This fails
User.query.update({User.score: _log(User)})

SQLAlchemy 的 func 让你告诉 SQLAlchemy 使用哪个数据库函数,例如 postgresql 确实支持 log(),所以你应该可以用 func.log() 调用它,但那将是由数据库执行查询。如果你想让它由 Python 执行,你只需要调用 math.log().

https://www.postgresql.org/docs/13/functions-math.html