Gof*_*tty 5 postgresql psycopg2 flask-sqlalchemy alembic flask-migrate
我有一个这样的模型:
class Schedule(db.Model):
__tablename__ = 'schedule'
id = db.Column(db.Integer, primary_key=True)
student_id = db.Column(ARRAY(db.Integer, db.ForeignKey('student.id')))
Run Code Online (Sandbox Code Playgroud)
然后我将student_id列更改为如下所示:
student_id = db.Column(db.Integer, db.ForeignKey('student.id'))
Run Code Online (Sandbox Code Playgroud)
这是我的迁移文件的片段:
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy.dialects.postgresql import INTEGER
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
# ...
op.alter_column('schedule', 'student_id',
existing_type=postgresql.ARRAY(INTEGER()),
type_=sa.Integer(),
existing_nullable=True)
# ...
# ### end Alembic commands ###
Run Code Online (Sandbox Code Playgroud)
当我尝试运行db migrate命令时,我收到以下错误消息:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.DatatypeMismatch) column "student_id" cannot be cast automatically to type integer
HINT: You might need to specify "USING student_id::integer".
[SQL: 'ALTER TABLE schedule ALTER COLUMN student_id TYPE INTEGER ']
Run Code Online (Sandbox Code Playgroud)
我的软件包版本是:
Flask==0.12
alembic==0.8.10
Flask-Migrate==2.0.3
Flask-SQLAlchemy==2.1
SQLAlchemy==1.1.5
psycopg2==2.8.3
Run Code Online (Sandbox Code Playgroud)
当我尝试使用以下命令直接在 SQL 上运行时:
ALTER TABLE schedule ALTER COLUMN student_id TYPE INTEGER;
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息:
ERROR: column "student_id" cannot be cast automatically to type integer
HINT: You might need to specify "USING student_id::integer".
SQL state: 42804
Run Code Online (Sandbox Code Playgroud)
然后我尝试添加带有HINT指令的命令:
ALTER TABLE schedule ALTER COLUMN student_id TYPE INTEGER USING student_id::integer;
Run Code Online (Sandbox Code Playgroud)
然后我得到这个错误:
ERROR: cannot cast type integer[] to integer
LINE 1: ...ER COLUMN student_id TYPE INTEGER USING student_id::integer;
^
SQL state: 42846
Character: 75
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是,这有什么问题..?Alembic 或我的代码中直接有任何问题吗?请任何帮助,我们将不胜感激:)
我通过遵循@a_horse_with_no_name注释来遵循此指令来弄清楚这一点。
所以,我的问题的答案是,我直接在 PostgreSQL 上运行以下命令:
alter table schedule alter column student_id set data type int4 using (student_id[1]::int)
Run Code Online (Sandbox Code Playgroud)
非常感谢@a_horse_with_no_name :)
| 归档时间: |
|
| 查看次数: |
6047 次 |
| 最近记录: |