【问题标题】:Alembic cannot be cast automatically to type integer [duplicate]Alembic 无法自动转换为整数类型 [重复]
【发布时间】:2020-01-13 00:23:16
【问题描述】:

我有一个这样的模型:

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')))

然后我将student_id 列改成这样:

student_id = db.Column(db.Integer, db.ForeignKey('student.id'))

这是我的迁移文件的 sn-p:

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 ###

当我尝试运行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 ']

我的包版本是:

Flask==0.12
alembic==0.8.10
Flask-Migrate==2.0.3
Flask-SQLAlchemy==2.1
SQLAlchemy==1.1.5
psycopg2==2.8.3

当我尝试使用此命令直接在 SQL 上运行时:

ALTER TABLE schedule ALTER COLUMN student_id TYPE INTEGER;

我收到此错误消息:

ERROR:  column "student_id" cannot be cast automatically to type integer
HINT:  You might need to specify "USING student_id::integer".
SQL state: 42804

然后我尝试用HINT指令添加命令:

ALTER TABLE schedule ALTER COLUMN student_id TYPE INTEGER USING student_id::integer;

然后我得到了这个错误:

ERROR:  cannot cast type integer[] to integer
LINE 1: ...ER COLUMN student_id TYPE INTEGER USING student_id::integer;
                                                             ^
SQL state: 42846
Character: 75

所以,我的问题是,这有什么问题..?Alembic 或直接在我的代码中是否有任何问题..? 请,任何帮助将不胜感激:)

【问题讨论】:

  • 如果你想将一个数组(=多个值)转换为一个整数(=单个值),你需要告诉 Postgres 取数组的哪个元素。 stackoverflow.com/questions/56753071
  • 非常好的建议,非常感谢 Man :)

标签: postgresql flask-sqlalchemy psycopg2 alembic flask-migrate


【解决方案1】:

我通过关注 @a_horse_with_no_name 评论来关注这个instruction

所以,我的问题的答案是,我直接在 PostgreSQL 上运行了以下命令:

alter table schedule alter column student_id set data type int4 using (student_id[1]::int)

非常感谢 @a_horse_with_no_name :)

【讨论】:

    猜你喜欢
    • 2012-10-21
    • 1970-01-01
    • 2023-03-28
    • 2013-04-07
    • 2012-12-20
    • 2021-01-26
    • 2016-06-04
    • 2020-08-11
    • 2019-02-26
    相关资源
    最近更新 更多