【问题标题】:Alembic default value to be used in add_column在 add_column 中使用的 Alembic 默认值
【发布时间】:2016-04-25 00:05:56
【问题描述】:

如何让 alembic 为新列使用指定的默认值,而不将其设为 server_default

只有现有的行应该接收这个默认值。之后插入的新行仍应为server_default

【问题讨论】:

    标签: sqlalchemy alembic


    【解决方案1】:

    我遇到了类似的问题,我希望新列不能为空,这当然不适用于现有行。因此,我首先创建了没有非空约束的行,用一些自定义 python 代码填充了该列,然后更改了该列(在同一迁移中)以具有约束。

    因此,您将遍历现有对象,根据瞬态默认值设置值。

    【讨论】:

      【解决方案2】:

      您必须使用server_default,但您需要以与数据库处理相同的格式将值作为字符串传递。

      https://docs.sqlalchemy.org/en/13/core/metadata.html#:~:text=server_default%20%E2%80%93,server%20side%20defaults

      例如:

      op.add_column('users', sa.Column('created_at', sa.DateTime(), nullable=False, server_default=str(datetime.now())))
      

      查看 miguelgrinberg 在这里所说的内容:

      https://github.com/miguelgrinberg/Flask-Migrate/issues/265#:~:text=The%20server_default%20should%20be%20given%20as%20text%20in%20the%20native%20format%20of%20the%20database%2C%20not%20as%20a%20Python%20type.%20See%20https%3A//docs.sqlalchemy.org/en/13/core/metadata.html%23sqlalchemy.schema.Column.params.server_default.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-24
        • 2022-11-29
        • 2019-08-17
        • 1970-01-01
        • 2012-08-01
        • 2021-12-20
        相关资源
        最近更新 更多