[英]Selectively performing mathematical calculation on InstrumentedAttribute in Flask/SQLAlchemy
I'm working with the Flask / SQLAlchemy ORM and what I'd like to do is to perform mathematical calculations selectively on instances of sqlalchemy.orm.attributes.InstrumentedAttribute
.我正在使用 Flask/SQLAlchemy ORM,我想做的是对
sqlalchemy.orm.attributes.InstrumentedAttribute
实例有选择地执行数学计算。 An equation like this would look something like User.query.update({User.score: User.points / User.time})
.像这样的等式看起来像
User.query.update({User.score: User.points / User.time})
。
For example, let's say I have > 100,000 entries in my PostgreSQL database that looks something like this: User.points
--> [12, 3, 0, ..., 45];例如,假设我的 PostgreSQL 数据库中有 > 100,000 个条目,如下所示:
User.points
--> [12, 3, 0, ..., 45]; User.time
--> [102, 23, 45, ..., 12] (please note the 0
in User.points
). User.time
--> [102, 23, 45, ..., 12] (请注意User.points
的0
)。 In the example below, I would get an exception stating I cannot take the logarithm of 0.在下面的示例中,我会收到一个异常,说明我不能取 0 的对数。
from sqlalchemy import func
from project.models import User
User.query.update({User.score: func.log(User.points / User.time)})
I'd like to selectively choose which InstrumentAttribute
to perform calculations on.我想有选择地选择要对其执行计算的
InstrumentAttribute
。 I can use User.query.filter
to filter a query, but how would I transform this into a filtered model without performing calculations iteratively, if you will?我可以使用
User.query.filter
来过滤查询,但是如果您愿意,我将如何将其转换为过滤模型而不迭代执行计算?
db.session.query(User).where(User.points != 0).update({User.score: func.log(User.points / User.time)})
// or
User.query.filter(User.points != 0).update({User.score: func.log(User.points / User.time)})
db.session.commit()
logs:日志:
2021-07-20 20:20:25,750 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2021-07-20 20:20:25,754 INFO sqlalchemy.engine.Engine UPDATE "user" SET score=log("user".points / "user".time) WHERE "user".points != %(points_1)s
2021-07-20 20:20:25,754 INFO sqlalchemy.engine.Engine [no key 0.00046s] {'points_1': 0}
2021-07-20 20:20:25,764 INFO sqlalchemy.engine.Engine UPDATE "user" SET score=log("user".points / "user".time) WHERE "user".points != %(points_1)s
2021-07-20 20:20:25,764 INFO sqlalchemy.engine.Engine [no key 0.00055s] {'points_1': 0}
2021-07-20 20:20:25,766 INFO sqlalchemy.engine.Engine COMMIT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.