SQLAlchemy filter query “column LIKE ANY (array)”

后端 未结 2 1577
清歌不尽
清歌不尽 2020-12-09 18:23

Hi SQLAlchemy experts out there, here\'s a tricky one for you:

I\'m trying to write a query that resolves into something like:

SELECT * FROM MyTable          


        
相关标签:
2条回答
  • 2020-12-09 19:27

    You can try to use any_()

    In your case it would look something like this:

    from sqlalchemy import any_
    
    foo = ['a%', 'b%']
    DBSession().query(MyTable).filter(MyTable.my_column.like(any_(foo)))
    
    0 讨论(0)
  • 2020-12-09 19:28

    Use or_() and like(), the following code should satisfy your need well:

    from sqlalchemy import or_
    
    foo = ['a%', 'b%']
    DBSession().query(MyTable).filter(or_(*[MyTable.my_column.like(name) for name in foo]))
    

    A where condition WHERE my_column LIKE 'a%' OR my_column LIKE 'b%' would be generated from above code.

    As for why your any() didn't work, I think it's because it requires my_column to be a list (see here), and, for instance, query(MyTable).filter(MyTable.my_list_column.any(name='abc')) is to return MyTable rows if any element in my_list_column column (a list) of that row is named with 'abc', so it's actually quite different from your need.

    0 讨论(0)
提交回复
热议问题