简体   繁体   中英

How to search for multiple values in column with Sqlalchemy postgres

I have a query in PostgreSQL that searches and selects all the rows with values '0' or '3' inside an arrayed column called 'news'. This column has an array of multiple values. For example:

id   | country | news
--------------------- 
one  | xyz     | {'2','4','8'}
two  | esc     | {'0','4','2'}
three| eec     | {'9','3','5'}

So,

SELECT * FROM table WHERE news && '{"0", "3"}';

results in row two and three being selected. Perfect. But I need to do this in sqlalchemy.

Does anyone know how this can be written in SQLalchemy?

@balderman helped me with resources that I used to come up with this sqlalchemy code:

full_id_list = []
for n in ['0','3']:
    ids = db.session.query(table).filter(table.news.op('@>')([n]))
    full_id_list.append(booklist)

But is there a simpler way, without using a for Loop?

参见https://docs.sqlalchemy.org/zh/13/dialects/postgresql.html#sqlalchemy.dialects.postgresql.ARRAY.Comparator

query = session.query(table).filter(table.news.contains([some_int])).all()

Solved it, finally.

db.session.query(Table).filter(Table.news.op('&&')(['0','3']))

All I had to do is change the operation (.op) from @> to &&, because && means you can search for multiple values inside a column with an array of values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM