74

I've got a query:

MyModel.query.filter(Mymodel.name.contains('a_string'))

I need to do the same query but with the negation (a not like operator) but didn't find any operator matching my need in the SQLAlchemy documentation.

Is there any way to do it without using the sql part of SQLAlchemy???

Jérôme Pigeot
  • 2,091
  • 4
  • 22
  • 25

2 Answers2

112

Just negate the filter:

MyModel.query.filter(sqlalchemy.not_(Mymodel.name.contains('a_string')))
Maxim Sloyko
  • 15,176
  • 9
  • 43
  • 49
  • 63
    Or `MyModel.query.filter(~Mymodel.name.contains('a_string'))` – Vroo Feb 03 '13 at 18:19
  • Right answer give Vroo. 'Contains' not have same functional as LIKE operator. If you want compatibility with sql code you need use this variant with '~' – erroia Apr 09 '18 at 09:29
  • [Link to docs](https://docs.sqlalchemy.org/en/13/core/sqlelement.html?highlight=not_#sqlalchemy.sql.expression.not_) – George Mauer Aug 29 '19 at 18:15
14

There is now a notlike() method. Couldn't find it in the docs but it exists!

MyModel.query.filter(Mymodel.name.notlike('%a_string%'))
Jossy
  • 589
  • 2
  • 12
  • 36