How can I get the list of affected rows (objects) when sending an update query with SQLAlchemy?

Question:

I wish to update multiple items/rows/objects with an update query. But this query does not seem to return any objects after executing it. How can I get back the list with affected objects. For example with a query like this:

session.query(my_model).filter(
    my_model.status == 'OK',
    my_model.is_validated == True,
    my_model.expires_at <= plum_dt.now(),
).update({'status':'EXPIRED'})

I wish to get back the list with the updated objects. If I just add all() at the end for the query it does not return anything.

Asked By: KZiovas

||

Answers:

do you try this?:

 qry = session.query(my_model).filter(
       my_model.status == 'OK',
       my_model.is_validated == True,
       my_model.expires_at <= plum_dt.now(),
   )
 
 elements_to_update = qry.all()
 
 qry.update({'status':'EXPIRED'})
Answered By: Ektorr

Ok this might be an incidental way to get a response back from the update method but you can get back information for the updated columns by using a synchronize_session='fetch' in the update method.

So the original query would be like:

session.query(my_model).filter(
    my_model.status == 'OK',
    my_model.is_validated == True,
    my_model.expires_at <= plum_dt.now(),
).update({'status':'EXPIRED'}, synchronize_session="fetch")

More details can be found in the documentation.

Answered By: KZiovas