SQLAlchemy-在Postgresql中执行批量更新(如果存在,更新或插入)

发布于 2021-01-29 18:16:36

我正在尝试使用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的任何记录,然后插入新记录,但是对于我的情况来说,这似乎很昂贵,因为我不希望有很多更新。

关注者
0
被浏览
252
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看