from aenum import Enum
class CompanyType(Enum):
type1 = 1
type2 = 2
class Company(BaseModel):
__tablename__ = 'company'
company_type = db.Column(db.Enum(CompanyType), default=CompanyType.type1, nullable=False)
奇怪的是我已经有了另一个带有枚举字段的模型,它工作正常,在数据库本身中创建了变量。但我不记得当时我具体做了什么。 这次当我尝试使用 alembic 更新数据库时遇到了异常。
sqlalchemy.exc.ProgrammingError:(psycopg2.errors.UndefinedObject)类型“companytype”不存在 第 1 行:ALTER TABLE company ADD COLUMN type companytype NOT ... ^
[SQL: ALTER TABLE company ADD COLUMN type companytype NOT NULL] (此错误的背景位于:http://sqlalche.me/e/13/f405)
Alembic 生成的代码是:
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('company', sa.Column('type', sa.Enum('type1', 'type2', name='companytype'), nullable=True))
# ### end Alembic commands ###
我有一种感觉,我必须说数据库来创建这个变量,但我不知道如何。
更新
我找到了一个解决方法。事实证明,只有当表已经存在时才会出现该问题。因此,我创建了一个具有相同列的临时表,并且脚本在数据库中生成了枚举变量。然后我删除了该表并将该列添加到我的公司表中,它终于起作用了。不确定这是否是一个错误,以及是谁的错误。
您遇到的问题是 Alembic 中的bug。目前,当
upgrade
已经存在时,您需要手动更改 Enum
函数才能成功升级数据库:
from sqlalchemy.dialects import postgresql
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
companytype_enum = postgresql.ENUM('type1', 'type2', name='companytype', create_type=False)
companytype_enum.create(op.get_bind(), checkfirst=True)
op.add_column('company', sa.Column('type', companytype_enum, nullable=True))
# ### end Alembic commands ###
对于那些寻找简单、有效且与后端无关的解决方案的人,请参阅我在另一个问题中的回答。
下面的代码适用于我的情况
def upgrade():
companytype = sa.Column('type', sa.Enum('type1', 'type2', name='companytype')
companytype.create(op.get_bind())
op.add_column('company', companytype, nullable=True))