python - sqlalchemy.exc.IntegrityError:(psycopg2.errors.UniqueViolation)重复键值违反唯一约束“product_pkey”
问题描述
def insert_from_query(self, model, query, **replace):
# The SQLAlchemy core definition of the table
table = inspect(model).local_table
# and the underlying core select statement to source new rows from
print(type(query))
select = query.statement
# validate asssumptions: make sure the query produces rows from the above table
assert table in select.froms, f"{query!r} must produce rows from {model!r}"
assert all(c.name in select.columns for c in table.columns), f"{query!r} must include all {model!r} columns"
# updated select, replacing the indicated columns
as_clause = lambda v: literal(v) if not isinstance(v, ClauseElement) else v
replacements = {name: as_clause(value).label(name) for name, value in replace.items()}
from_select = select.with_only_columns([replacements.get(c.name, c) for c in table.columns])
insert_statement = table.insert().from_select(from_select.columns, from_select)
insert = self.engine.execute(insert_statement)
return insert
我正在尝试在产品表中更新一个名为“activity_id”的字段时进行批量插入。
生成的语句就是这样做的,但是我遇到了 IntegrityError
错误跟踪:
sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "product_pkey"
DETAIL: Key (id)=(210776) already exists.
我基本上是在复制现有条目,并且只是更新它们的 activity_id,但是当使用一个更新的字段创建这些克隆条目时activity_id
,我认为它也应该增加该字段id
,我认为它现在试图克隆该字段。在我的数据库中,它被标记为主键/索引。
解决方案
推荐阅读
- android - 如何从命令行复制 Android 虚拟设备 (AVD)?
- php - 从 PHP 中的嵌套 JSON 获取数据
- r - 如何将循环结果保存在多个 csv r
- javascript - 运行 Node 应用程序的 Heroku 错误 R14(超出内存配额)
- python - Pandas Dataframe:检查满足条件的特定行
- r - 在R中的函数中更改名称
- angular - 角度接受文件从计算机拖放到 div
- python-3.x - 将字符串与python中的多个字符串进行比较
- python-3.x - 删除python项目的脚本文件夹
- node.js - Node.js 在 typeorm 的实体中添加 created_at 和 updated_at