SQLAlchemy查询将id标记为null

问题描述 投票:0回答:1

我正在使用SQLAlchemy在表中插入一行。该表的定义如下:

class MyTable():
    __table__ = "my_table"
    id = Column(BigInteger, primary_key=True)
    stuff1 = Column(Numeric)

这是炼金术线:

MyTable(stuff1=100)

这是它生成的查询:

INSERT INTO my_table (id, stuff1) VALUES (null, 100)

我得到这个错误:

IntegrityError('(psycopg2.IntegrityError) null value in column \"id\" violates not-null constraint

由于id是主键,我希望它能自动生成。但似乎我必须手动应用序列吗?我究竟做错了什么?

python postgresql sqlalchemy
1个回答
1
投票

这种情况在我之前发生过,通常我要么没有使用sqlalchemy来创建表,要么我在sqlalchemy中的表定义不完整/不正确。如果您有一个'create table if not exists'设置,那么您的更改将不会与postgres中的表定义同步。我将使用psql命令行工具检出表定义,以验证是否未为主键设置服务器默认值。它应该是串行数据类型或使用外部序列。

© www.soinside.com 2019 - 2024. All rights reserved.