SQLAlchemy-在Postgresql中执行批量更新(如果存在,更新或插入)
我正在尝试使用SQLAlchemy模块(而不是SQL!)在python中编写大量upsert。
我在SQLAlchemy添加上遇到以下错误:
sqlalchemy.exc.IntegrityError: (IntegrityError) duplicate key value violates unique constraint "posts_pkey"
DETAIL: Key (id)=(TEST1234) already exists.
我有一个称为列posts
的主键的表id
。
在此示例中,我已经在数据库中使用了一行id=TEST1234
。当我尝试将db.session.add()
新对象id
设置TEST1234
为时,出现上述错误。我的印象是,如果主键已经存在,记录将得到更新。
我如何仅基于主键就可以对Flask-SQLAlchemy进行增补? 有没有简单的解决方案?
如果没有,我总是可以检查并删除具有匹配ID的任何记录,然后插入新记录,但是对于我的情况来说,这似乎很昂贵,因为我不希望有很多更新。
-
SQLAlchemy中有一个upsert-esque操作:
db.session.merge()
找到此命令后,我可以执行upsert,但是值得一提的是,对于批量“ upsert”而言,此操作很慢。
另一种方法是获取您要向上插入的主键的列表,并在数据库中查询任何匹配的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()