Flask SQLAlchemy中如何指定USING start_time::timestamp without time zone?
解决Flask SQLAlchemy修改列类型时的USING语句问题
当你需要把Show模型的start_time列从String改为DateTime时,Flask-Migrate生成的默认迁移脚本缺少PostgreSQL要求的类型转换规则,导致执行flask db upgrade报错。正确的处理方式是手动修改迁移脚本,添加USING子句:
- 运行
flask db migrate生成初始迁移文件后,打开该文件(路径通常为migrations/versions/[随机字符串]_.py) - 找到针对
start_time列的alter_column代码段,默认代码类似:
op.alter_column('show', 'start_time', existing_type=sa.String(), type_=sa.DateTime(timezone=False), existing_nullable=True)
- 为该语句添加
postgresql_using参数,指定字符串转时间戳的转换规则:
op.alter_column('show', 'start_time', existing_type=sa.String(), type_=sa.DateTime(timezone=False), existing_nullable=True, postgresql_using='start_time::timestamp without time zone')
- 保存修改后,执行
flask db upgrade即可完成列类型修改
注意事项
- 如果你的
start_time字符串格式不是PostgreSQL默认可识别的时间格式,需要用to_timestamp函数适配,比如字符串是YYYY/MM/DD HH:MM格式,就把postgresql_using的值改为to_timestamp(start_time, 'YYYY/MM/DD HH24:MI') - 不要直接删除重建列,尤其是列中已有业务数据时,这种方式会丢失数据,添加
USING子句的原地修改是更安全的方案
内容的提问来源于stack exchange,提问作者user15377952
相关产品推荐
相关产品推荐

