简体   繁体   English

如何更改alembic中列的索引

[英]How to alter index of a column in alembic

in version: 0001, I create a table users like below:在版本:0001 中,我创建了一个用户表,如下所示:

def upgrade():
    op.create_table(
        'users',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('email', sa.String(length=255), nullable=False),
        sa.PrimaryKeyConstraint('id')
    )

    op.create_index(op.f('ix_user_email'), 'users', ['email'], unique=True)

def downgrade():
    op.drop_table('users')

In version 0020, I want to alter the index of column email in users table.在版本 0020 中,我想更改 users 表中 email 列的索引。 In this case, I want unique=False .在这种情况下,我想要unique=False Is there a way better than:有没有比以下更好的方法:

def upgrade():
    op.drop_index(op.f('ix_user_email'))
    op.create_index(op.f('ix_user_email'), 'users', ['email'], 
    unique=False)
def downgrade():
    op.drop_index(op.f('ix_user_email'))

Because of doing this, when downgrade to version 0019 column ['email'] don't have index at all.因为这样做,当降级到版本 0019 列 ['email'] 根本没有索引。

So if there is a way to alter back and forth the index of column email.因此,如果有办法来回更改列电子邮件的索引。 It's gonna be better.它会更好。

You could restore the original index by adjusting the downgrade() method in 0020 to re-create it:您可以通过调整 0020 中的downgrade()方法来恢复原始索引以重新创建它:

def downgrade():
    op.drop_index(op.f('ix_user_email'))
    # re-create previous version of index
    op.create_index(op.f('ix_user_email'), 'users', ['email'], unique=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM