我试图使用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的记录,然后插入新记录,但这对我来说似乎很昂贵,因为我不希望有很多更新。
在SQLAlchemy中有一个upsert类型的操作:
db.session.merge()
在我找到这个命令之后,我可以执行upsert,但是值得一提的是,对于大容量的“upsert”,这个操作很慢。
另一种方法是获取要追加插入的主键的列表,并查询数据库以获取任何匹配的ID:
相关问题 更多 >
编程相关推荐