以下SQLAlchemy代码可以正常工作,但看起来不是pythonic:
if has_died: # has_died: True or False
query = query.filter(User.died_at != None)
else:
query = query.filter(User.died_at == None)
添加过滤器的更优雅方式是什么?
答案 0 :(得分:4)
嗯,你可以这样做:
query = query.filter((User.died_at != None) if has_died else (User.died_at == None))
但它有点难以阅读。我想你是怎么做的。
答案 1 :(得分:3)
您可以将其重写为一行ternary operator
query = query.filter((User.died_at != None) if has_died else (User.died_at == None))
答案 2 :(得分:0)
怎么样:
query = query.filter(bool(User.died_at) == has_died)
它返回:
False
如果User.died_at
为None
且has_died
为True
True
如果User.died_at
为None
且has_died
为False
True
如果User.died_at
不是None
且has_died
是True
False
如果User.died_at
不是None
且has_died
是False
这是预期的行为......
但话又说回来,不确定它比你的代码更容易理解!