alphanumeric
alphanumeric

Reputation: 19379

How to use filter operators with SQLAlchemy

With SQLAlchemy I can query filtering the result with endswith method:

session.query(MyObject).filter(MyObject.uuid.endswith("z")).all()

Similar with startswith:

session.query(MyObject).filter(MyObject.uuid.startswith("a")).all()

contains follows the same syntax:

session.query(MyObject).filter(MyObject.uuid.contains('c')).all()

I wonder if == and != operators could be replaced with the similar syntax. So, instead of:

 session.query(MyObject).filter(MyObject.uuid=='cfbb4cdb57').all()

it would be something like:

session.query(MyObject).filter(MyObject.uuid.is('cfbb4cdb57')).all()

Upvotes: 0

Views: 3616

Answers (1)

ACV
ACV

Reputation: 1985

Yes.

There is .is_() and .isnot() as well as calling .__eq__() explicitly.

However, note that is and == are not the same in Python. From PEP8:

Comparisons to singletons like None should always be done with is or is not , never the equality operators

So, I think you would want to use == (not __eq__) for non-singletons and is_() for comparing against None.

The full list of what are called queryable attributes is here.

Upvotes: 2

Related Questions