我在Python3下使用Flask开发了一个web应用程序。我在db migrate / upgrade上遇到postgresql枚举类型的问题。
我添加了一个列" status"建模:
class Banner(db.Model):
...
status = db.Column(db.Enum('active', 'inactive', 'archive', name='banner_status'))
...
python manage.py db migrate
生成的迁移是:
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('banner', sa.Column('status', sa.Enum('active', 'inactive', 'archive', name='banner_status'), nullable=True))
def downgrade():
op.drop_column('banner', 'status')
当我python manage.py db upgrade
时,我收到错误:
...
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) type "banner_status" does not exist
LINE 1: ALTER TABLE banner ADD COLUMN status banner_status
[SQL: 'ALTER TABLE banner ADD COLUMN status banner_status']
为什么迁移不会创建类型" banner_status"?
我做错了什么?
$ pip freeze
alembic==0.8.6
Flask==0.10.1
Flask-Fixtures==0.3.3
Flask-Login==0.3.2
Flask-Migrate==1.8.0
Flask-Script==2.0.5
Flask-SQLAlchemy==2.1
itsdangerous==0.24
Jinja2==2.8
Mako==1.0.4
MarkupSafe==0.23
psycopg2==2.6.1
python-editor==1.0
requests==2.10.0
SQLAlchemy==1.0.13
Werkzeug==0.11.9
答案 0 :(得分:43)
我决定用这个问题。
我更改了迁移和迁移的代码,如下所示:
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
banner_status = postgresql.ENUM('active', 'inactive', 'archive', name='banner_status')
banner_status.create(op.get_bind())
op.add_column('banner', sa.Column('status', sa.Enum('active', 'inactive', 'archive', name='banner_status'), nullable=True))
def downgrade():
op.drop_column('banner', 'status')
banner_status = postgresql.ENUM('active', 'inactive', 'archive', name='banner_status')
banner_status.drop(op.get_bind())
现在python manage.py db upgrade\downgrade
已成功执行。
答案 1 :(得分:2)
我认为这种方式更简单:
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
# others_column = ...
banner_status = postgresql.ENUM('active', 'inactive', 'archive', name='banner_status', create_type=False), nullable=False)
如果需要,还可以将postgresql.ENUM
添加到您的downgrade()
函数中。