【问题标题】:How to change the length of a Primary Key field in Alembic?如何更改 Alembic 中主键字段的长度?
【发布时间】:2019-02-24 16:51:41
【问题描述】:

我正在尝试将主键字段的长度从 3 更改为 6。

型号:

class Server(db.Model):
    country_code = db.Column(db.String(6), primary_key=True)

迁移:

def upgrade():
    op.alter_column('server', 'country_code',
               existing_type=mysql.VARCHAR(length=3),
               type_=sa.String(length=6))

但是我收到此错误消息,我不太明白,为什么它认为我将其更改为 null。

_mysql_exceptions.DataError: (1171, 'PRIMARY KEY 的所有部分都必须不是 NULL;如果您需要在键中使用 NULL,请改用 UNIQUE')

【问题讨论】:

    标签: python mysql alembic


    【解决方案1】:

    您需要先移除列的主键属性,然后才能更改其数据类型。

    def upgrade():
        # Drop primary key constraint.
        op.execute('ALTER TABLE user DROP PRIMARY KEY')
    
        # Change type of the primary key column.
        op.alter_column('server', 'country_code',
                        existing_type=mysql.VARCHAR(length=3),
                        type_=sa.String(length=6))
    
        # Re-create the primary key constraint.
        op.create_primary_key(None, 'server', ['country_code'])
    

    【讨论】:

      猜你喜欢
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      • 2020-01-24
      • 2013-01-28
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多