How to use NOT IN clause in sqlalchemy ORM query

The ORM internals describe the not_in() operator (previously notin_()), so you can say:

query = query.filter(
#                               ^^^^^^

From the docs:

inherited from the ColumnOperators.not_in() method of ColumnOperators

implement the NOT IN operator.

This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).

Note that version 1.4 states:

The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

So you may find notin_() in some cases.

Leave a Comment