简体   繁体   中英

How to replace Postgres array elements using SQLAlchemy ORM?

Suppose we have a Postgres table with an integer array column xs :

create table mytable (
    id bigserial primary key,
    xs int[]
);

Using Postgres 9.4 and SQLAlchemy 1.0.14, I want to replace a single value (for example 123 ) in all of rows in xs column. What I have now is a raw SQL query that looks like

update mytable set xs = array_replace(xs, 123, 456) where 123 = any(xs)

The 123 = any(xs) is just to speed up query as otherwise we would replace all rows not regarding whether the interesting value is in the array or not.

How could I rewrite the above query using the SQLAlchemy ORM when I already have MyTable mapped?

Assuming you're using the correct postgresql.ARRAY type:

from sqlalchemy import  func

session.query(MyTable).\
    filter(MyTable.xs.any(123)).\
    update({MyTable.xs: func.array_replace(MyTable.xs, 123, 456)},
           synchronize_session=False)

Change the synchronization as necessary.

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