如何在SQLAlchemy中将多个外键映射到同一父项?

1 投票
1 回答
2273 浏览
提问于 2025-04-16 22:14

当我在同一张表中添加第二个外键时,出现了以下错误:

Please specify the 'onclause' of this join explicitly.

我该如何指定这个关系呢?

class Parent(Base):
    First = Column(Integer, ForeignKey('Child.Ex1'))
    Second = Column(Integer, ForeignKey('Child.Ex2'))

class Child(Base):
    Ex1 = Column(Integer)
    Ex2 = Column(Integer)

1 个回答

1

(编辑说明:pep8 建议类的属性名称以小写字母开头……这只是一个约定俗成的规则)

class Parent(Base):
    __tablename__ = "Parent"
    id = Column(Integer, primary_key=True)
    first = Column("First", Integer, ForeignKey('Child.Ex1'))
    second = Column("Second", Integer, ForeignKey('Child.Ex2'))

    first_child = relationship("Child", primaryjoin="Parent.first==Child.ex1")
    second_child = relationship("Child", primaryjoin="Parent.second==Child.ex2")

class Child(Base):
    __tablename__ = "Child"
    id = Column(Integer, primary_key=True)
    ex1 = Column("Ex1", Integer)
    ex2 = Column("Ex2", Integer)

撰写回答