gpt4 book ai didi

sqlalchemy - 无法在 sqlalchemy 中对 @hybrid_property 应用过滤器

转载 作者:行者123 更新时间:2023-12-01 23:13:17 24 4
gpt4 key购买 nike

代码很简单:

Class A(Base):
status = Columns(Integer)

@hybrid_property
def is_ok(self):
return self.status > 0


session.query(A).filter(A.is_ok).all()

将引发异常: TypeError: Boolean value of this clause is not defined .

我试过 print result[0].is_ok, type(result[0].is_ok) .它是 True <type 'bool'> .

那么如何根据 hybrid_property 进行过滤?

我的回答

在@van 的帮助下,我知道该怎么做。

arg filter(*criterion) 需要一个 SQL expression object .我曾经认为它需要一个 bool 值作为参数, 但不是!

The criterion is any SQL expression object applicable to the WHERE clause of a select. String expressions are coerced into SQL expression constructs via the text() construct.



代码告诉:
# wrong code:
@is_ok.expression
def is_ok(self):
return self.status > 30 and self.status < 90

# correct code:
from sqlalchemy.sql import and_
@is_ok.expression
def is_ok(self):
return and_(self.status > 30, self.status < 90).label('is_ok')

最佳答案

添加自定义表达式。以下使用 CASE声明,但您可以使用 IF如果你的数据库支持它:

@is_ok.expression
def is_ok(cls):
return case([(cls.status > 0, True)], else_=False).label("is_ok")

Defining Expression Behavior Distinct from Attribute Behavior 文档以获取更多信息。

关于sqlalchemy - 无法在 sqlalchemy 中对 @hybrid_property 应用过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23382489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com