Bulk saving complex objects SQLAlchemy

喜你入骨 提交于 2019-11-29 10:17:58

Session.bulk_save_objects() is too low level API for your use case, which is persisting multiple model objects and their relationships. The documentation is clear on this:

Warning

The bulk save feature allows for a lower-latency INSERT/UPDATE of rows at the expense of most other unit-of-work features. Features such as object management, relationship handling, and SQL clause support are silently omitted in favor of raw INSERT/UPDATES of records.

Please read the list of caveats at Bulk Operations before using this method, and fully test and confirm the functionality of all code developed using these systems.

You should use Session.add_all() to add a collection of instances to the session. It will handle the instances one at a time, but that is the price you have to pay for advanced features such as relationship handling.

So, instead of

session.bulk_save_objects(showtime_lists)
session.commit()

do

session.add_all(showtime_lists)
session.commit()

You can assign ids manually:

  1. Get a write lock on the table

  2. Find the highest existing id

  3. Manually generate an increasing sequence of ids

Instead of locking the table, you might be able to increment the id sequence in the database to "reserve" a block of ids.

You'll have to insert in the proper order to avoid foreign key violations (or defer the constraints if your engine allows this).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!