优雅的方式来过滤无或不过滤

时间:2015-08-18 11:45:53

标签: python sqlalchemy

以下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)

添加过滤器的更优雅方式是什么?

3 个答案:

答案 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_atNonehas_diedTrue
  • True如果User.died_atNonehas_diedFalse
  • True如果User.died_at不是Nonehas_diedTrue
  • False如果User.died_at不是Nonehas_diedFalse

这是预期的行为......

但话又说回来,不确定它比你的代码更容易理解!