Many to many relationship in sqlAlchemy with two f

2019-08-20 12:08发布

问题:

I have these class models:

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()

Consedering that an application has 2 support levels, each level can have one or more than one team ( each support is a team).

When I run my script I get this error:

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.

In this case, I have a relationship many to many: an application is managed by two levels of support that are teams, and each support can manage more than one application. How to map this relationship correctly??