Search code examples
pythonsqlitepeewee

Reverse _contains() query in peewee


I have a sqlite3 db of Music which has a column named "Album". Is there a way peewee can query all rows where the Album is a substring of a given string str - NOT the other way round?

From what I can see, we can query rows where str is a substring of Album but not the other way round:

#This works
q_str='anthem for the '
query=Music.select().where((Music.ALBUMARTIST == album_artist) & (Music.ALBUM.contains(qstr)) )

However in my case q_str would be something like 'anthem for the underdog (bonus track version)'

So I would actually want to perform query like this:

#Query should return a row where Music.ALBUM is 'anthem for the underdog'

q_str='anthem for the underdog (bonus track version)'
query=Music.select().where((Music.ALBUMARTIST == album_artist) & (Music.ALBUM.is_in(qstr)) )

The _in() opertator only works with Lists which isn't suitable in my usecase


Solution

  • You can do it like this:

    from peewee import Value
    
    q_str='anthem for the underdog (bonus track version)'
    query = (Music
             .select()
             .where(
                 (Music.ALBUMARTIST == album_artist) & 
                 (Value(q_str).contains(Music.ALBUM))))