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

时间:2011-07-25 17:10:39

标签: python foreign-keys sqlalchemy clause

将第二个外键添加到同一个表后,我收到以下错误:

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 个答案:

答案 0 :(得分: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)