python - sqlalchemy 添加了新列和“UndefinedColumn”错误
问题描述
我正在将数据插入到远程 postgres 数据库中,并且最近在其中一个表中添加了一个新列,现在我在将新数据插入带有新列的表中时遇到此错误
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedColumn) column "build_name" of relation "DryRun" does not exist
LINE 1: ...tance_id, profile_name, host_box, default_config, build_name...
我尝试了我在网上找到的方法,例如设置nullable=True
或给它一个默认值default='Unknown'
,但仍然遇到同样的错误。
这是我的DryRun
模型。
class DryRun(Base):
__tablename__ = 'DryRun'
id = Column(Integer, primary_key=True, autoincrement=True)
instance_id = Column(Integer, nullable=True)
profile_name = Column(String, nullable=False)
host_box = Column(String, nullable=False)
default_config = Column(JSON, nullable=False)
build_name = Column(String, nullable=True)
解决方案
这最初是作为评论发布的。
问题是现在对象与数据库中的对象不同。您可以运行 ALTER TABLE 命令以在命令行工具 psql 中添加列,或使用 pgadmin GUI。如果您预计会有更多此类更改,请考虑阅读其他一些模块支持的迁移;例如,alembic:https ://alembic.sqlalchemy.org/en/latest/
仅添加一列,迁移很可能没有意义。以下是您的用例的 ALTER TABLE 命令示例:
# run this command to get to a text-based interface to your Postgres database
$ psql
# alter table command for your use-case:
ALTER TABLE "DryRun" ADD COLUMN build_name VARCHAR;
推荐阅读
- javascript - Bootstrap Tour 是否允许错误消息验证?
- mysql - 在单个 postgres 表中生成多个索引
- c# - 在 .NET Core 中的 ActionResult 之后调用方法
- typescript - 为什么打字稿会为装饰器转译死代码?
- java - 演示缓存的使用,包括 ArrayList、二维数组和基本循环
- php - 插入多值 MySQL 和 PHP
- php - 使用 PHP socket_write 发送空格
- python - 从 Cocoa 应用程序针对 Apple 的股票 python 运行 python 脚本
- regex - 这个涉及否定和前后修复的正则表达式可以改进吗?
- sql - SQL Server Management Studio - 只执行一个查询,而不是整个脚本?