2

Is there a way to avoid iterating through a query in sqlalchemy to do a simple update? As is seems this method is over processing for something that the DB should handle.

E.g. could this be avoided?

items = db_session.query(Item).filter_by(category_id=category.id).all()
for item in items:
    item.category_id = new_category_id
    db_session.add(item)
db_session.commit()

I'm looking for something like:

items = db_session.query(Item).filter_by(category_id=category.id).all()
items.update(category_id=new_category_id)
db_session.commit()

Thanks for any help on this.

davidism
  • 121,510
  • 29
  • 395
  • 339
Simon Otter
  • 173
  • 1
  • 3
  • 13
  • Use [`Query.update()`](http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.update) instead of all. Note your session synchronization requirements. – Ilja Everilä Aug 18 '16 at 20:07

0 Answers0