Python SQLAlchemy过滤器,substr,案例

Python SQLAlchemy过滤器,substr,案例,python,sqlalchemy,Python,Sqlalchemy,我可以在substr和filter中使用CASE语句吗 以下是我的要求: >> value = '00021050430' #here value is a database column >> query.filter((func.substr(value,case([(func.length(value) > 7,func.length(varying_value)-7+1))],else_=1),7)=='1050430') 我期望的结果是: >>

我可以在
substr
filter
中使用
CASE
语句吗

以下是我的要求:

>> value = '00021050430' #here value is a database column
>> query.filter((func.substr(value,case([(func.length(value) > 7,func.length(varying_value)-7+1))],else_=1),7)=='1050430')
我期望的结果是:

>> query.filter(func.substr(value,6,7))

上面抛出了一个错误。

这里不需要使用
CASE()
语句。只需使用Python:

query.filter(func.substr(value, 1 if len(value) > 7 else 1, 7) == '1050430')
这称为条件表达式;如果test\u expr else false\u expr,则将其构造为
true\u expr,其中如果
test\u expr
的计算结果为true,则使用
true\u expr
,否则使用
false\u expr
部分

如果
value
不是常量而是列引用,则需要使用
CASE()
语句。用于:

from sqlalchemy.sql.expression import case

query.filter(func.substr(value, case([(func.length(column) > 7, func.length(column) - 7 + 1)], else_=1), 7) == '1050430')

但是你需要确保你的
括号是平衡的(你的括号太多了)。

请始终包括实际(完整)回溯。