首页 > 解决方案 > 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,我认为它现在试图克隆该字段。在我的数据库中,它被标记为主键/索引。

标签: pythonsqlalchemy

解决方案


推荐阅读