Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String matching in Peewee (SQL)

Tags:

sql

peewee

I am trying to query in Peewee with results that should have a specific substring in them.

For instance, if I want only activities with "Physics" in the name:

schedule = Session.select().join(Activity).where(Activity.name % "%Physics%").join(Course).join(StuCouRel).join(Student).where(Student.id == current_user.id)

The above example doesn't give any errors, but doesn't work correctly.

In python, I would just do if "Physics" in Activity.name, so I'm looking for an equivalent which I can use in a query.

like image 822
Ben Avatar asked Dec 14 '13 23:12

Ben


2 Answers

You could also use these query methods: .contains(substring), .startswith(prefix), .endswith(suffix).

For example, your where clause could be:

.where(Activity.name.contains("Physics"))

I believe this is case-insensitive and behaves the same as LIKE '%Physics%'.

like image 56
jhaskell Avatar answered Sep 30 '22 19:09

jhaskell


Quick answer:

just use Activity.name.contains('Physics')


Depending on the database backend you're using you'll want to pick the right "wildcard". Postgresql and MySQL use "%", but for Sqlite if you're performing a LIKE query you will actually want to use "*" (although for ILIKE it is "%", confusing).

I'm going to guess you're using SQLite since the above query is failing, so to recap, with SQLite if you want case-sensitive partial-string matching: Activity.name % "*Physics*", and for case-insensitive: Activity.name ** "%Physics%".

http://www.sqlite.org/lang_expr.html#like

like image 27
coleifer Avatar answered Sep 30 '22 21:09

coleifer