SQLAlchemy声明式关系配置:如何让两个关联都在Schema中显示
解决SQLAlchemy多外键关联可视化问题
你的问题是因为定义code1关系时没有明确指定对应的外键,SQLAlchemy无法自动匹配到Payments.code这个外键,导致可视化工具识别不到该关联。
修改后的代码如下:
class masters(Base): __tablename__='master' id = Column(Integer, primary_key=True) code = Column(String(128), nullable=False) class Payments(Base): __tablename__ = 'payments' code = Column(String(128), ForeignKey('master.code'), nullable=False, unique=True) source_id = Column(ForeignKey('master.id'), nullable=False) source = relationship('masters', primaryjoin='Payments.source_id == masters.id') code1 = relationship('masters', foreign_keys=[code])
关键说明:
- 当一个表与另一张表存在多个外键关联时,必须通过
foreign_keys参数明确指定当前关系对应的外键字段,SQLAlchemy才能正确绑定关联。 - 另外修正了
primaryjoin中的类名拼写(master.id改为masters.id),保持与类名一致更规范。
这样修改后,两个外键对应的关联都会被SQLAlchemy正确识别,数据库可视化工具就能显示出完整的关系Schema了。
内容的提问来源于stack exchange,提问作者sky
相关产品推荐
相关产品推荐

