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!
_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With