python - 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
解决方案
推荐阅读
- python - 无法启动 chrome 驱动程序
- javascript - 如何覆盖 JavaScript 方法
- python - 如何与 Python 中隐藏元素下的元素进行交互
- node.js - 使用节点在 mongodb 中列出集合时遇到问题
- regex - 正则表达式:日期格式(dd.mm.yyyy)的基本模式不起作用
- data-structures - sizeof 运算符给出错误结果
- xml - XSLT1:使用 xsl:element 如何包含当前选择的属性
- python - 如何在 PyTorch 中使用 TPU?
- ruby-on-rails - 我需要帮助来构建这个 Rails 应用程序
- assembly - 用 MUL 代替 DIV,为什么会这样?