SQLAlchemy-在postgresq中执行批量upsert(如果存在,则更新,否则插入)

2024-09-25 06:35:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用SQLAlchemy模块(而不是SQL!)在python中编写一个大容量upsert。

我在SQLAlchemy add上遇到以下错误:

sqlalchemy.exc.IntegrityError: (IntegrityError) duplicate key value violates unique constraint "posts_pkey"
DETAIL:  Key (id)=(TEST1234) already exists.

我有一个名为posts的表,在id列上有一个主键。

在这个例子中,我已经在数据库中有一行id=TEST1234。当我试图用id设置为TEST1234的新posts对象db.session.add()时,得到上面的错误。我的印象是,如果主键已经存在,记录就会更新。

如何仅基于主键使用烧瓶SQLAlchemy升级?有简单的解决办法吗?

如果没有,我总是可以检查并删除任何具有匹配id的记录,然后插入新记录,但这对我来说似乎很昂贵,因为我不希望有很多更新。


Tags: 模块addidsqlsqlalchemy错误记录exc
1条回答
网友
1楼 · 发布于 2024-09-25 06:35:25

在SQLAlchemy中有一个upsert类型的操作:

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()

相关问题 更多 >