【问题标题】:How to map multiple foreign keys to the same parent in SQLAlchemy?如何将多个外键映射到 SQLAlchemy 中的同一个父级?
【发布时间】:2011-10-12 18:51:50
【问题描述】:

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

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)

【问题讨论】:

    标签: python foreign-keys sqlalchemy clause


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

    【讨论】:

      猜你喜欢
      • 2014-04-16
      • 2014-06-15
      • 2015-01-29
      • 2022-01-16
      • 2013-07-03
      • 2019-09-08
      • 2010-11-20
      • 1970-01-01
      • 2011-08-10
      相关资源
      最近更新 更多