我正在尝试使用 Flask-SQLAlchemy 对 2 个表进行批量插入。这 2 个表是:
- 作者表:PK author_id(自增)
- 书表:PK book_id (ai), FK author_author_id
在 JSON 的正文中,我有一个字典列表。每个词典条目都有一些与作者相关的信息和一些与书籍相关的信息。像这样,可以一次性发送更多的词典:
[
{
"author_first_name": "John",
"author_last_name": "Doe",
"author_yob": "1988",
"book_name": "Mournings of a nun",
"book_genre": "Drama"
},
{
"author_first_name": "Jane",
"author_last_name": "Doe",
"author_yob": "1987",
"book_name": "Need for speed",
"book_genre": "Action"
}
]
目前,我正在遍历每个字典,将数据插入 author 表,然后插入 book 表。当我插入作者表并提交时,我得到一个主键,即 author_id。那是我的 book 表的外键。
我为这个列表中的每个条目重复这个步骤。有没有办法进行批量插入,这样如果任何插入失败,一切都会回滚,而且我的数据库中没有不一致的数据?因此,如果上面的 JSON 中有 15 个字典,如果第 12 个字典有一些无效数据或数据库出现故障,我希望 JSON 中发送的任何数据都不应发布到 AWS RDS。下面,“结果”指的是我上面提到的 JSON。
@classmethod
def post_to_database(cls, results):
for result in results:
BookModel.post_entry_to_database(result)
@classmethod
def post_entry_to_database(cls, result):
BookModel.insert_author_entry(result)
author_id = BookModel.get_author_id(result)
BookModel.insert_book_entry(author_id, result)
@classmethod
def insert_book_entry(cls, author_id, result):
book_data = BookModel(result["testname"], result["result"], author_id)
db.session.add(book_data)
db.session.commit()
同样,我也有 insert_author_entry。
谢谢, 阿迪亚
最佳答案
您可以考虑使用 flush()
将更改刷新到数据库,这将更新您的主键字段。
来自 SqlAlchemy 文档:flush
Database operations will be issued in the current transactional context and do not affect the state of the transaction, unless an error occurs, in which case the entire transaction is rolled back. You may flush() as often as you like within a transaction to move changes from Python to the database’s transaction buffer.
当调用 flush
时,数据库会将您的 CRUD 操作保持在事务中待处理,并且不会永久保留,直到数据库收到当前事务的 COMMIT
。这将在您随后调用 commit()
时发生。
关于python - 使用 SQLAlchemy ORM 批量插入多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53788885/