我正在使用 MySQL 8.0 和 SQLAlchemy。我的 id 列没有增加,我不明白为什么。
SQLAlchemy 模型:
class Show(db.Model):
__tablename__ = "shows"
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
type = Column(String)
status = Column(String)
episodes = Column(Integer)
series_entry_id = Column(Integer, ForeignKey("series.id"))
series_id = Column(Integer, ForeignKey("series.id"))
lists = relationship("List", secondary=show_list, back_populates="shows")
recommendations = relationship("Recommendation", backref=backref("shows"))
user_ratings = relationship("Rating", backref=backref("shows"))
alt_names = relationship("User", secondary=alt_names, back_populates="alt_show_names")
series_entry = relationship("Series", foreign_keys=[series_entry_id], uselist=False)
series = relationship("Series", foreign_keys=[series_id], post_update=True)
破解代码:
show = Show(
name=new_data["title"]["english"],
type=new_data["format"],
status=new_data["status"],
episodes=new_data["episodes"],
)
db.session.add(show)
db.session.commit()
我收到的原始错误是:
sqlalchemy.exc.DatabaseError: (mysql.connector.errors.DatabaseError) 1364 (HY000): Field 'id' doesn't have a default value
根据这个答案,我将索引参数添加到我的 id 列中,并编辑 my.ini 文件以使其脱离 STRICT_TRANS_TABLES 模式。新的错误是:
sqlalchemy.exc.IntegrityError: (mysql.connector.errors.IntegrityError) 1062 (23000): Duplicate entry '0' for key 'shows.PRIMARY'
我在该主题中找到的所有答案都涉及 AUTO_INCRMENT,但 SQLAlchemy 文档说这应该是这里的默认值,因为它是一个整数主键,没有指定为 false。我确实尝试添加 autoincrement=True 以防万一,但是当我尝试迁移它时,alembic 告诉我没有检测到任何更改。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
从评论到问题:
不,这确实是它的工作原理。具体来说,对于像这样的模型
class Account(Base): __tablename__ = "account" account_number = Column(Integer, primary_key=True) customer_name = Column(String(50))alembic 修订版 --autogenerate将生成def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('account', sa.Column('account_number', sa.Integer(), nullable=False), sa.Column('customer_name', sa.String(length=50), nullable=True), sa.PrimaryKeyConstraint('account_number') )(没有显式指定
autoincrement=)但是当alembic 升级 head获取 SQLAlchemy 来实际创建 SQLAlchemy 发出的表CREATE TABLE account ( account_number INTEGER NOT NULL AUTO_INCREMENT, customer_name VARCHAR(50), PRIMARY KEY (account_number) )没有。如上所示,首次创建表时,Alembic 会正确处理
AUTO_INCRMENT。它没有检测到的是,具有现有表的 ORM 模型的列从autoincrement=False更改为autoincrement=True(反之亦然)。这是已知行为,如提交消息此处所示: p>
“请注意,此标志不支持更改列的“自动增量”状态,因为这不可跨后端移植。”
MySQL确实支持通过ALTER_TABLE更改列的AUTO_INCRMENT属性,因此我们可以通过更改“空”
upgrade方法来实现def upgrade(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ###至
def upgrade(): op.alter_column( 'account', 'account_number', existing_type=sa.Integer(), existing_nullable=False, autoincrement=True )渲染