2016-03-28 43 views
0

我想,以配合我已經在我的PostgreSQL數據庫的名稱一些名字,使用下面的代碼:如何在postgresql數組字段上使用ilike sqlalchemy?

last_like = '{last_name}%'.format(last_name) 
matches = Session.query(MyTable).filter(or_(
    MyTable.name.ilike(last_like), 
    MyTable.other_names.any(last_like, operator=ilike_op), 
)).all() 

本質上,它試圖name列匹配任何存儲其他的名字作爲other_names列中的數組。

,但我得到:

KeyError: <function ilike_op at 0x7fb5269e2500> 

我在做什麼錯?

回答

0

對於使用postgresql數組字段,您需要使用unnest()函數。 但是,您不能在where子句中使用unnest()的結果。可以使用array_to_string函數。在字符串other_names上搜索將產生相同的效果

from sqlalchemy import func as F 
last_like = "%qq%" 
matches = session.query(MyTable).filter(or_(
    MyTable.name.ilike(last_like), 
    F.array_to_string(MyTable.other_names, ',').ilike(last_like), 
)).all() 
相關問題