Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare Python list with Postgres Array in SQLAlchemy?

I have a column in my PSQL table type array of type integers, let's call the column tags.I have a Python list that has type integers, lets' call it categories.

How do I run a SQLAlchemy query so that I return any row in my table if the tags column has one or more matching integers to the categories array?

like image 765
Suraj Kapoor Avatar asked Sep 24 '26 09:09

Suraj Kapoor


1 Answers

Assuming that the list of categories is not very large, this is one way how to go about it using an OR of any(...) for each category:

q = db.session.query(MyTable)
clauses = [MyTable.tags.any(cat_id) for cat_id in categories]
q = q.filter(db.or_(*clauses))
for r in q.all():
    print(r)
like image 127
van Avatar answered Sep 28 '26 07:09

van



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!