Bulk insert with SQLAlchemy ORM

前端 未结 10 1102
刺人心
刺人心 2020-11-30 17:15

Is there any way to get SQLAlchemy to do a bulk insert rather than inserting each individual object. i.e.,

doing:

INSERT INTO `foo` (`bar`) VALUES (1         


        
相关标签:
10条回答
  • 2020-11-30 18:08

    Direct support was added to SQLAlchemy as of version 0.8

    As per the docs, connection.execute(table.insert().values(data)) should do the trick. (Note that this is not the same as connection.execute(table.insert(), data) which results in many individual row inserts via a call to executemany). On anything but a local connection the difference in performance can be enormous.

    0 讨论(0)
  • 2020-11-30 18:13

    SQLAlchemy introduced that in version 1.0.0:

    Bulk operations - SQLAlchemy docs

    With these operations, you can now do bulk inserts or updates!

    For instance, you can do:

    s = Session()
    objects = [
        User(name="u1"),
        User(name="u2"),
        User(name="u3")
    ]
    s.bulk_save_objects(objects)
    s.commit()
    

    Here, a bulk insert will be made.

    0 讨论(0)
  • 2020-11-30 18:16

    Piere's answer is correct but one issue is that bulk_save_objects by default does not return the primary keys of the objects, if that is of concern to you. Set return_defaults to True to get this behavior.

    The documentation is here.

    foos = [Foo(bar='a',), Foo(bar='b'), Foo(bar='c')]
    session.bulk_save_objects(foos, return_defaults=True)
    for foo in foos:
        assert foo.id is not None
    session.commit()
    
    0 讨论(0)
  • 2020-11-30 18:17

    I usually do it using add_all.

    from app import session
    from models import User
    
    objects = [User(name="u1"), User(name="u2"), User(name="u3")]
    session.add_all(objects)
    session.commit()
    
    0 讨论(0)
提交回复
热议问题