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
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.
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.
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()
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()