简体   繁体   English

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

[英]Elegant way to filter by none or not none

The following SQLAlchemy code works, but looks un-pythonic: 以下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)

What is a more elegant way to add the filter? 添加过滤器的更优雅的方法是什么?

Well, you could do this: 好吧,你可以这样做:

query = query.filter((User.died_at != None) if has_died else (User.died_at == None))

But it's a bit hard to read. 但它有点难以阅读。 I think how you're doing it is fine. 我想你是怎么做的很好。

您可以使用三元运算符将其重写为一行

query = query.filter((User.died_at != None) if has_died else (User.died_at == None))

What about: 关于什么:

query = query.filter(bool(User.died_at) == has_died)

It returns: 它返回:

  • False if User.died_at is None and has_died is True 如果User.died_atNonehas_diedTrueUser.died_at False
  • True if User.died_at is None and has_died is False True如果User.died_atNonehas_diedFalse
  • True if User.died_at is not None and has_died is True True如果User.died_atNonehas_diedTrue
  • False if User.died_at is not None and has_died is False False如果User.died_atNonehas_diedFalse

Which is the intended behavior... 这是预期的行为......

But then again, not sure if it is easier to understand than your piece of code! 但话说回来,不确定它是否比你的代码更容易理解!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM