如何在SQLAlchemy中为ORM类的底层视图表传入动态参数
SQLAlchemy动态参数视图映射实现方案
有两种常用的特性可以实现该需求:
方案1:使用bindparam构造参数占位符
这是最贴合你原有写法的实现方式,通过bindparam在固定的视图查询中预留参数位,查询时再传入具体值:
from sqlalchemy import bindparam, DATE class Aggregation(Base): __table__ = ( select( func.sum(OtherTable.amount).label("amount"), OtherTable.currency, ) # 定义名为cutoff_date的参数占位符,可指定类型做校验 .where(OtherTable.created < bindparam("cutoff_date", type_=DATE)) .group_by(OtherTable.currency) .alias() )
查询时通过params方法传入参数即可:
# 查询创建时间早于2024-01-01的聚合数据 res = session.query(Aggregation).params(cutoff_date="2024-01-01").all()
方案2:动态生成查询子句
如果参数较多、逻辑灵活度要求高,可以不把查询逻辑固定在__table__属性中,改为封装动态生成查询的方法:
class Aggregation(Base): # 预先声明映射字段 amount = Column(Numeric) currency = Column(String, primary_key=True) @classmethod def get_agg_query(cls, cutoff_date, session): sub_query = ( select( func.sum(OtherTable.amount).label("amount"), OtherTable.currency, ) .where(OtherTable.created < cutoff_date) .group_by(OtherTable.currency) .subquery() ) return session.query(sub_query)
调用时直接传入参数获取查询结果:
res = Aggregation.get_agg_query("2024-01-01", session).all()
注意:映射类的
__table__属性会在类加载阶段就完成编译生成固定结构,无法在运行时直接修改,因此不能直接通过修改类属性的方式传入动态参数。
内容的提问来源于stack exchange,提问作者Rol
相关产品推荐
相关产品推荐

