【问题标题】:SQLAlchemy add condition to querySQLAlchemy 为查询添加条件
【发布时间】:2015-12-30 10:47:35
【问题描述】:

我的原始 sql 语句的开头如下所示:

select if(substr(Table.order_id,1,8)='STRING', Table1.name, t=Table2.type)

试图在 SQLAlchemy 查询中重写它:

query = db_session.query(Table,\ 
                         Table1.name if Table.order_id[1:8] == 'STRING' else Table2.type)

但它返回了Operator 'getitem' is not supported on this expression

如何在不接触模型的情况下将此条件添加到我的 ORM 查询中?

或者如何在查询参数中添加原始 sql 语句?

PS:我不希望对模型进行任何更改。

【问题讨论】:

    标签: python mysql flask sqlalchemy


    【解决方案1】:

    你需要使用Functions:

    from sqlalchemy import func
    
    q = db_session.query(
        func.IF(func.substr(Table.order_id, 1, 8) == 'STRING', Table1.name, Table2.type)
    )
    

    【讨论】:

    • 我不确定substr(?, 1, 8) 通常的长度为 6(STRING 也是如此)
    • 原始字符串长度为 8,我的错误。完美,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多