2

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.