sqlAlchemy中的多对多关系,其中两个外键指向同一个表

时间:2018-06-28 12:35:06

标签: python mysql sqlalchemy foreign-keys many-to-many

我有以下课程模型:

class Application(Base):
    __tablename__ = 'applications'
    identifier = Column(Integer, primary_key=True)
    name = Column(String)
    description = Column(String)

    level1 = relationship("Teams", secondary='assoc_apps_teams', back_populates='support_1')
    level2 = relationship("Teams", secondary='assoc_apps_teams', back_populates='support_2')


class Teams(Base):
    __tablename__ = 'teams'

    identifier = Column(Integer, primary_key=True)
    name = Column(String)
    description = Column(String)

    support_1 = relationship("Application", secondary='assoc_apps_teams', back_populates='level1')
    support_2 = relationship("Application", secondary='assoc_apps_teams', back_populates='level2')


class AssocAppsTeams(Base, DictSerializable):
    __tablename__ = 'assoc_apps_teams'

    identifier = Column(Integer, primary_key=True)
    apps_id = Column(Integer, ForeignKey("applications.identifier"), nullable=False) 
    support1_id = Column(Integer, ForeignKey("teams.identifier"), nullable=False) 
    support2_id = Column(Integer, ForeignKey("teams.identifier"), nullable=False) 

if __name__ == "__main__":
  app = model.Application("app", "desc")
  session.add(app)    
  session.commit()
  session.close()

考虑到一个应用程序有2个支持级别,每个级别可以有一个或多个团队(每个支持是一个团队)。

运行脚本时出现此错误:

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Applications.support1 - there are multiple foreign key paths linking the tables via secondary table 'assoc_apps_levels'.  Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference from the secondary table to each of the parent and child tables.

在这种情况下,我之间的关系是多对多的:一个应用程序由团队的两个支持级别管理,每个支持可以管理多个应用程序。如何正确映射这种关系?

0 个答案:

没有答案