Markus N.
Markus N.

Reputation: 330

Operator "NOT LIKE" with peewee

I would need a query where the content "IS NOT LIKE" a value for

query = (Table
                .select()
                .where((Table.lastseen < olddate.isoformat()) &
                       (Table.used==1) &
                       (Table.ip !% '%/%' ))
                .order_by(Table.lastseen.asc())
            )

The ! doesn't do the trick, how do i get the LIKE negated?

Upvotes: 1

Views: 1046

Answers (1)

python_user
python_user

Reputation: 7083

You have to use ~ instead of !. That is how negation works in peewee. You need to wrap the query you wish to negate using parenthesis. In your case (~(Table.ip % '%/%' )).

query = (Table
                .select()
                .where((Table.lastseen < olddate.isoformat()) &
                       (Table.used==1) &
                       (~(Table.ip % '%/%' )))
                .order_by(Table.lastseen.asc())
            )

Minimum Reproducible Example (Snippet taken from peewee docs)

from datetime import date
from peewee import *

db = SqliteDatabase('people.db')

class Person(Model):
    name = CharField()
    birthday = DateField()

    class Meta:
        database = db # This model uses the "people.db" database.

db.connect()
db.create_tables([Person])

uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15))
uncle_bob.save()
aunt_alice = Person(name='Alice', birthday=date(1965, 1, 15))
aunt_alice.save()

query = Person.select().where(~(Person.name % 'B*')) # not like 'B%', wildcard changes according to database, `*` instead of `%` for SQLite

for i in query:
    print(i.name) # Alice

Upvotes: 2

Related Questions