【问题标题】:Taking logarithm of value using SQLAlchemy - Flask/SQLAlchemy [duplicate]使用 SQLAlchemy 取值的对数 - Flask/SQLAlchemy [重复]
【发布时间】:2021-09-26 05:57:15
【问题描述】:

我正在尝试将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 连接到 sqlite 注册任意函数。

标签: python python-3.x sqlite flask sqlalchemy


【解决方案1】:

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

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

【讨论】:

  • 是的,从 SQLite 迁移到 PostgreSQL 并应用 func.log() 是要走的路。
猜你喜欢
  • 2015-02-02
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 2018-09-14
  • 1970-01-01
  • 2015-03-01
相关资源
最近更新 更多