You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Alembic为何将所有模型字段设为nullable=False?

SQLAlchemy模型与Alembic自动迁移的字段可空性问题

我的SQLAlchemy模型定义如下:

class Base(DeclarativeBase):
    pass


class AppUser(Base):
    __tablename__ = "app_user"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    created_at: Mapped[DateTime] = mapped_column(DateTime, default=func.now())
    updated_at: Mapped[DateTime] = mapped_column(
        DateTime,
        default=func.now(),
        onupdate=func.now(),
    )
    telegram_id: Mapped[int] = mapped_column(BigInteger, unique=True, index=True)
    telegram_username: Mapped[str] = mapped_column(String(60), unique=True, index=True)
    language: Mapped[str] = mapped_column(String(10), default="en")
    comment: Mapped[str] = mapped_column(String(255))

执行命令:

pdm run alembic revision --autogenerate -m "Create a baseline migrations"

生成的迁移脚本如下:

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('app_user',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('created_at', sa.DateTime(), nullable=False),
    sa.Column('updated_at', sa.DateTime(), nullable=False),
    sa.Column('telegram_id', sa.BigInteger(), nullable=False),
    sa.Column('telegram_username', sa.String(length=60), nullable=False),
    sa.Column('language', sa.String(length=10), nullable=False),
    sa.Column('comment', sa.String(length=255), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_app_user_id'), 'app_user', ['id'], unique=False)
    op.create_index(op.f('ix_app_user_telegram_id'), 'app_user', ['telegram_id'], unique=True)
    op.create_index(op.f('ix_app_user_telegram_username'), 'app_user', ['telegram_username'], unique=True)
    # ### end Alembic commands ###

我没有做任何配置让telegram_id、telegram_username、language和comment字段不可为空。SQLAlchemy默认是nullable=True,按道理Alembic应该遵循这个规则,但生成的迁移脚本里这些字段都被设为nullable=False了,而且我在Alembic文档里也没找到这种默认行为的说明。

内容的提问来源于stack exchange,提问作者wsaxton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 13:43:13