首页 > 解决方案 > 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)

标签: pythonpostgresqlsqlalchemy

解决方案


这最初是作为评论发布的。

问题是现在对象与数据库中的对象不同。您可以运行 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;

推荐阅读