我正在try 使用SQLAlchemy模块(而不是SQL!)用python编写一个批量升级.

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

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

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

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

How can I upsert with Flask-SQLAlchemy based on primary key alone? Is there a simple solution?

如果没有,我可以随时判断并删除任何具有匹配id的记录,然后插入新记录,但这对于我的情况来说似乎很昂贵,因为我不希望有太多更新.

推荐答案

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

Postgresql相关问答推荐

Postgres SQL执行加入

PostgreSQL:函数结果表内冲突(...)上的";中的字段名称

在Docker容器内的Postgres,如何通过Promail将JSON登录到Loki?

在PostgreSQL中是否有与SQLite R*Tree类似功能?

时间戳的postgreSQL-to_char如果为零,则不显示微秒

为什么 Postgres 中的 now() 和 now()::timestamp 对于 CET 和 CEST 时区如此错误?

PostgreSQL中如何在同一行中存储多个与单个值相关的ID?

如何使用 Grafana 测量 PostgreSQL 中的复制

如何获取在 Go 中完成的 SQL 插入的错误详细信息?

Regexp_replace 行为会改变,如果它用空白字符串或 null 替换字符串数组中的字符串

在 Ubuntu 11.04 服务器中启用对 postgresql 的 PHP 支持

计算 PostgreSQL 中给定 GPS 坐标的日出和日落时间

包含受先前 DELETE 影响的行数的变量?

断言错误:Django-rest-Framework

当记录包含 json 或字符串的混合时,如何防止 Postgres 中的invalid input syntax for type json

按任意时间间隔计算行数的最佳方法

python postgres 我可以 fetchall() 100 万行吗?

如何使用 PostgreSQL 在任何列中查找所有具有 NULL 值的行

从 5 分钟前的表中获取行

如何为本地 Rails 元素设置 Postgres 数据库?