Using bulk_update_mappings in SQLAlchemy to update multiple rows with different values

前端 未结 1 1674
耶瑟儿~
耶瑟儿~ 2021-02-07 03:19

I have two tables Foo and Bar. I just added a new column x to the Bar table which has to be populated using values in Foo

class Foo(Base):
    __tab         


        
1条回答
  •  心在旅途
    2021-02-07 03:37

    The approach is correct in terms of usage. The only thing I would change is something like below

    mappings = []
    i = 0
    
    for b, foo_x in session.query(Bar, Foo.x).join(Foo, Foo.id==Bar.foo_id):
        info = {'id':b.id, 'x': foo_x}
        mappings.append(info)
        i = i + 1
        if i % 10000 == 0:
            session.bulk_update_mappings(Bar, mappings)
            session.flush()
            session.commit()
            mappings[:] = []
    
    session.bulk_update_mappings(Bar, mappings)
    

    This will make sure you don't have too much data hanging in memory and you don't do a too big insert to the DB at a single time

    0 讨论(0)
提交回复
热议问题