Sqlalchemy how to filter a column that contains both null and integer values

I have a table with a null column that contains both types of Null values ​​(default) and integer:

class Node(db.Model): __tablename__ = "node" maintenance = db.Column(db.Integer, nullable=True) 

The request is as follows:

 maintenance = 1 node_list = Node.query.filter(Node.maintenance != maintenance).all() 

I need to select all cells containing Null or 0 values.

Thank you in advance!

+6
source share
1 answer

I need to select all cells containing the values ​​"Null" or "0".

Using | as a logical OR

 Node.query.filter((Node.maintenance == None) | (Node.maintenance == 0)) 

Using is_(None)

Or, to avoid using == None (due to lint)

 Node.query.filter((Node.maintenance.is_(None)) | (Node.maintenance == 0)) 

Using or_

Or this form

 from sqlalchemy import or_ Node.query.filter(or_(Node.maintenance == None, Node.maintenance == 0)) 

Using in_

If you are wondering if you can request the use of something similar to the in operator in SQL and Python, you are correct, you can do it in SQLAlchemy too, but unfortunately it does not work for None/NULL values , but for illustration we can see that

 Node.query.filter(Node.maintenance.in_([0, 1])) 

equivalently

 Node.query.filter((Node.maintenance == 0) | (Node.maintenance == 1)) 
+8
source

All Articles