You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PonyORM中create_tables=False时映射现有关联表报错如何解决?

Pony ORM关联现有数据库表时的配置缺失问题

我来帮你解决这个问题!你用Pony ORM映射两张已存在的关联表时,碰到了这样的错误:

psycopg2.ProgrammingError: column structures.system does not exist
LINE 1: ...ctures"."structure_id", "structures"."system_id", "structure...

HINT: Perhaps you meant to reference the column "structures.system_id".

这是因为你在Structure类里的配置有冲突,没有正确告诉Pony ORM要使用数据库中已有的system_id列作为关联外键。

先看你原来的代码:

from pony.orm import *
db = Database()

class System(db.Entity):
    _table_ = 'some', 'systems'
    system_id = PrimaryKey(int, auto=True)
    structures = Set('Structure')

class Structure(db.Entity):
    _table_ = 'some', 'structures'
    structure_id = PrimaryKey(int, auto=True)
    system_id = Required(int)
    system = Required(System)

db.bind(...)
db.generate_mapping(create_tables=False)

错误原因

当你定义system = Required(System)时,Pony ORM默认会尝试在structures表中寻找名为system的列作为外键,但你的实际数据库里只有system_id这个外键列,同时你还手动定义了system_id = Required(int),这就导致了Pony ORM的映射逻辑和实际数据库结构不匹配。

正确的配置方案

你需要明确指定关联属性system对应的数据库外键列是system_id,有两种常用的修改方式:

方式一:移除手动定义的system_id,直接指定关联列

如果你不需要在代码中直接操作system_id字段,可以这样写:

class Structure(db.Entity):
    _table_ = 'some', 'structures'
    structure_id = PrimaryKey(int, auto=True)
    # 通过column参数告诉Pony,这个关联对应数据库里的system_id列
    system = Required(System, column='system_id')

方式二:保留system_id字段,关联到它

如果需要在代码中直接访问system_id,可以配置关联属性时指定对应的列:

class Structure(db.Entity):
    _table_ = 'some', 'structures'
    structure_id = PrimaryKey(int, auto=True)
    system_id = Required(int)
    # 指定system关联使用已有的system_id列,同时通过reverse关联到System的structures集合
    system = Required(System, reverse='structures', column='system_id')

这样修改后,Pony ORM就能正确映射到数据库中已存在的structures.system_id列,不会再去找不存在的structures.system列了。

内容的提问来源于stack exchange,提问作者dmigo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:57:27