我正在尝试使用 SQLAlchemy 模块(而不是 SQL!)在 python 中编写批量更新插入。
我在 SQLAlchemy 添加中收到以下错误:
sqlalchemy.exc.IntegrityError: (IntegrityError) duplicate key value violates unique constraint "posts_pkey"
DETAIL: Key (id)=(TEST1234) already exists.
我有一张桌子叫posts
上有一个主键id
column.
在这个例子中,我已经在数据库中有一行id=TEST1234
。当我尝试db.session.add()
一个新的 posts 对象id
set to TEST1234
,我收到上面的错误。我的印象是,如果主键已经存在,记录就会更新。
如何仅基于主键使用 Flask-SQLAlchemy 更新插入?有一个简单的解决方案吗?
如果没有,我总是可以检查并删除具有匹配 id 的任何记录,然后插入新记录,但这对于我的情况来说似乎很昂贵,我不希望有很多更新。
SQLAlchemy 中有一个 upsert 式的操作:
db.session.merge()
找到这个命令后,我能够执行更新插入,但值得一提的是,对于批量“更新插入”来说,此操作很慢。
另一种方法是获取您想要更新插入的主键列表,并在数据库中查询任何匹配的 id:
# 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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)