Thorben Croisé
Thorben Croisé

Reputation: 12870

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?

Upvotes: 4

Views: 2322

Answers (3)

Challensois
Challensois

Reputation: 542

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
  • True if User.died_at is None and has_died is False
  • True if User.died_at is not None and has_died is True
  • False if User.died_at is not None and has_died is False

Which is the intended behavior...

But then again, not sure if it is easier to understand than your piece of code!

Upvotes: 0

SuperBiasedMan
SuperBiasedMan

Reputation: 9969

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

Upvotes: 3

Cyphase
Cyphase

Reputation: 12002

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.

Upvotes: 5

Related Questions