Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlalchemy how to filter column which contains both Null and integer values

Tags:

I have table with a nullable column which contains both types of values Null (as default) and integer:

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

The request is like this one:

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

I need to select all cells which contains Null or 0 values.

Thank you in advance!

like image 419
Alex Gore Avatar asked May 25 '16 18:05

Alex Gore


People also ask

What is _sa_instance_state in SQLAlchemy?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.

Are SQLAlchemy columns nullable by default?

Columns are nullable by default The default value of SQLAlchemy nullable is False unless it's a primary key. A foreign key is also nullable by default.

What is lazy dynamic SQLAlchemy?

lazy = 'dynamic': When querying with lazy = 'dynamic', however, a separate query gets generated for the related object. If you use the same query as 'select', it will return: You can see that it returns a sqlalchemy object instead of the city objects.


1 Answers

I need to select all cells which contains 'Null' or '0' values.

Using | as the logical OR

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

Using is_(None)

Or, to avoid using == None (because of linters)

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 are wondering if you can query using something akin to the in operator in SQL and Python, you're right you can do it in SQLAlchemy too, but unfortunately it doesn't work for None/NULL values, but to illustrate we can see that

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

is equivalent to

Node.query.filter((Node.maintenance == 0) | (Node.maintenance == 1)) 
like image 154
bakkal Avatar answered Sep 28 '22 07:09

bakkal