您可以将autoincrement 属性设置为False 以获得此效果*。这段代码
import sqlalchemy as sa
meta = sa.MetaData()
tbl = sa.Table('test20210102a', meta,
sa.Column('id', sa.Integer, primary_key=True, autoincrement=False),
sa.Column('name', sa.String(8)))
engine = sa.create_engine('postgresql+psycopg2:///test', echo=True)
meta.drop_all(bind=engine)
meta.create_all(bind=engine)
with engine.connect() as conn:
conn.execute(tbl.insert({'name': 'foo'}))
engine.dispose()
在创建表时发出此警告
SAWarning: Column 'test20210102a.id' is marked as a member of the primary key for table 'test20210102a', but has no Python-side or server-side default generator indicated, nor does it indicate 'autoincrement=True' or 'nullable=True', and no explicit value is passed. Primary key columns typically may not store NULL.
并产生此错误
sqlalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, foo).
* 上面的代码应该适用于大多数 RDBMS。 Sqlite 具有不同的自动增量语义,如dialect information 中所述,但您可以通过对 id 列使用不同的整数类型来获得类似的行为:
sa.Column('id', sa.SmallInteger, primary_key=True, autoincrement=False)