pythonfilternullsqlmodel

sqlmodel: filter by null


Referring to the filtering examples here: https://sqlmodel.tiangolo.com/tutorial/where/#filter-rows-using-where-with-sqlmodel, how do I fetch all heroes whose age is null.

I need the equivalent of:

select * from hero where age is null

This works:

select(Hero).where(Hero.age != None)

but, IDE complains PEP 8: E711 comparison to None should be 'if cond is not None:'

So I changed it to:

select(Hero).where(Hero.age is None)

but, it does not work as intended causing an incorrect SQL to generate:

SELECT * FROM hero WHERE 0 = 1

What is the right approach?


Solution

  • from sqlalchemy.sql.operators import is_
    
    
    stmt = select(Hero).where(is_(Hero.age, None))
    result = session.exec(stmt)