问题是这样的:
News.label == None and f(News.title) == 'good'# ^^^ here
Python不允许覆盖布尔 操作
and和的行为
or。您可以
__bool__在Python
3和
__nonzero__Python
2中在一定程度上影响它们,但所做的只是定义对象的真实值。
如果有问题的对象没有实现
__bool__并抛出错误,或者实现没有抛出,则由于and的短路特性
and``or,您可能会获得相当神秘的错误:
In [19]: (News.label == 'asdf') and TrueOut[19]: <sqlalchemy.sql.elements.Binaryexpression object at 0x7f62c416fa58>In [24]: (News.label == 'asdf') or TrueOut[24]: True
因为
In [26]: bool(News.label == 'asdf')Out[26]: False
这可能并且将导致以不正确的SQL表达式的形式出现问题:
In [28]: print(News.label == 'asdf' or News.author == 'NOT WHAT YOU EXPECTED')news.author = :author_1
为了产生布尔SQL表达式要么使用
and_(),
or_()和
not_()SQL表达式的功能,或二进制
&,
|和
~操作者重载:
# Parentheses required due to operator precedencefilter((News.label == None) & (f(News.title) == 'good'))
要么
filter(and_(News.label == None, f(News.title) == 'good'))
或将多个条件传递给对的调用
Query.filter():
filter(News.label == None, f(News.title) == 'good')
或组合多个呼叫至
filter():
filter(News.label == None).filter(f(News.title) == 'good')



