首页 > 解决方案 > sqlalchemy.exc.IntegrityError:(psycopg2.errors.NotNullViolation)列“id”中的空值违反非空约束

问题描述

我正在尝试在我的数据库中执行批量插入。

我有一张桌子叫products

其中有product_id、category_id、属性、列。

我也有一id列,但我已经通过我的映射器将它的列设置为自动递增。

products = \
    Table('products ',
          metadata,
          Column('id', Integer, primary_key=True, autoincrement=True),
          Column('product_id', Integer),
          Column('category_id', Integer),
          schema=schema)
mapper(model.product, products )

当我尝试像这样批量插入该表时,我已经在我的数据库管理器中的每个列中添加了索引。我正在使用 Navicat。

def bulk_save_objects(self, products):
        def save_query(count):
            return f"""
            INSERT INTO products (product_id, category_id, attributes)
            VALUES (:{count}, :{count + 1}, :{count + 2})
            """
        queries = []
        params = {}
        count = 1
        for product in products:
            queries.append(save_query(count))
            params[str(count)] = product.product_id
            params[str(count + 1)] = product.category_id
            params[str(count + 2)] = product.attributes
            count += 3

        self.session.execute(';'.join(queries), params)

我收到以下错误:

sqlalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) null value in column "id" violates not-null constraint

model/products.py
class Products:
    def __init__(self, product_id, category_id, attributes = {}):
        self.product_id = simulation_id
        self.category_id = category_id
        self.attributes = attributes

标签: pythonpostgresql

解决方案


推荐阅读