使用sqlalchemy_utils ChoiceType在Flask中迁移时出错

我有一个Flask模型:

class User(db.Model):
    ROLE_USER = 0
    ROLE_MODERATOR = 1
    ROLE_ADMIN = 2
    ROLES = [
        (ROLE_USER, u'Regular user'),
        (ROLE_MODERATOR, u'Moderator'),
        (ROLE_ADMIN, u'Admin')
    ]

    id = db.Column(db.Integer, primary_key = True)
    login = db.Column(db.String(32), nullable=False, unique=True)
    first_name = db.Column(db.String(32))
    last_name = db.Column(db.String(32))
    role = db.Column(ChoiceType(ROLES), nullable=False)

我用flask-migrate创建了一个迁移(db是Postgresql):

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('user',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('login', sa.String(length=32), nullable=False),
    sa.Column('first_name', sa.String(length=32), nullable=True),
    sa.Column('last_name', sa.String(length=32), nullable=True),
    sa.Column('role', sqlalchemy_utils.types.choice.ChoiceType(length=255), nullable=False),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('login')
    )

迁移是成功创建的,但是当我想升级时,这个错误就会上升:

TypeError: <flask_script.commands.Command object at 0x7fada1e973d0>: __init__() got an unexpected keyword argument 'length'

有人能解释一下这个问题吗?

最佳答案 正如错误所说,ChoiceType没有名为length的init参数:

http://sqlalchemy-utils.readthedocs.org/en/latest/data_types.html#module-sqlalchemy_utils.types.choice

您可以将其删除并使用

sqlalchemy_utils.types.choice.ChoiceType(User.ROLES)

代替.

点赞