Efficiently updating database using SQLAlchemy ORM

前端 未结 6 1382
梦毁少年i
梦毁少年i 2020-11-28 01:14

I\'m starting a new application and looking at using an ORM -- in particular, SQLAlchemy.

Say I\'ve got a column \'foo\' in my database and I want to increment it.

6条回答
  •  死守一世寂寞
    2020-11-28 01:18

    Withough testing, I'd try:

    for c in session.query(Stuff).all():
         c.foo = c.foo+1
    session.commit()
    

    (IIRC, commit() works without flush()).

    I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of queries. I assume that iterating over the query object is less efficient than iterating over a list generated by the all() method of the query object.

    [Please note comment below - this did not speed things up at all].

提交回复
热议问题