Search code examples
pythonpostgresqlsqlalchemy

How to update SQLAlchemy Postgres array at a single element?


There is no docs for ARRAY field update in sqlalchemy. Idk, how to update position by index in sqlachemy orm. There is only possible to update the whole array, but I need to update single element in entry.

I found example in postgres docs:

SELECT * FROM sal_emp;
 name  |      pay_by_quarter       |                 schedule
-------+---------------------------+-------------------------------------------
 Bill  | {10000,10000,10000,10000} | {{meeting,lunch},{training,presentation}}
 Carol | {20000,25000,25000,25000} | {{breakfast,consulting},{meeting,lunch}}
UPDATE sal_emp SET pay_by_quarter[4] = 15000
WHERE name = 'Bill';

But I didn't find how to slice or index in .values method, there is only keyword arguments supported.

# sqlalchemy

update(SalEmp).values(pay_by_quarter=???).where(SalEmp.name=='Bill')

# Can't do like this:

update(SalEmp).values(SalEmp.pay_by_quarter[4]=15000).where(SalEmp.name=='Bill')

Solution

  • You can do this by passing a dict such as {SalEmp.pay_by_quarter[4]: 15000} to values.

    The ORM query looks like

    update(SalEmp).values({SalEmp.pay_by_quarter[4]: 15000}).where(SalEmp.name=='Bill')