复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16# Imagine that post1, post5, and post1000 are posts objects with ids 1, 5 and 1000 respectively # The goal is to "upsert" these posts. # we initialize a dict which maps id to the post object my_new_posts = {1: post1, 5: post5, 1000: post1000} for each in posts.query.filter(posts.id.in_(my_new_posts.keys())).all(): # Only merge those posts which already exist in the database db.session.merge(my_new_posts.pop(each.id)) # Only add those posts which did not exist in the database db.session.add_all(my_new_posts.values()) # Now we commit our modifications (merges) and inserts (adds) to the database! db.session.commit()
参考
https://stackoverflow.com/questions/25955200/sqlalchemy-performing-a-bulk-upsert-if-exists-update-else-insert-in-postgr
最后
以上就是粗暴书包最近收集整理的关于sqlalchemy 批量插入或更新的全部内容,更多相关sqlalchemy内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复