Bulk insert with SQLAlchemy ORM

前端 未结 10 1103
刺人心
刺人心 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: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()
    

提交回复
热议问题