Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to filter by none or not none

The following SQLAlchemy code works, but looks un-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?

like image 800
Thorben Croisé Avatar asked Mar 15 '23 01:03

Thorben Croisé


2 Answers

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.

like image 111
Cyphase Avatar answered Mar 27 '23 21:03

Cyphase


You could rewrite it as one line with a ternary operator

query = query.filter((User.died_at != None) if has_died else (User.died_at == None))
like image 45
SuperBiasedMan Avatar answered Mar 27 '23 22:03

SuperBiasedMan