【问题标题】:SQLAlchemy require primary key to be generated by programSQLAlchemy 要求程序生成主键
【发布时间】:2021-01-02 17:21:01
【问题描述】:

定义表时,将一列定义为primary_key=True。如tutorial 所示,SQLAlchemy 将自动为项目创建一个 ID,即使它不是由用户提供的。 primary_key=True 也会自动设置nullable=False

有没有一种方法可以设置主键以便它是必需的,但不是由 SQLAlchemy 填充?我希望我的程序为每一行提供一个主键。

类似:

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, autogenerate=False)
    name = Column(String)
    nickname = Column(String)

【问题讨论】:

    标签: python sql sqlalchemy flask-sqlalchemy


    【解决方案1】:

    您可以将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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-02
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多