是否有可能建立这样的关系:
class Games(Base):
publishers = relationship(GameCompany).where(GameCompany.role == 'publisher')
developers = relationship(GameCompany).where(GameCompany.role == 'developer')
基本上,创建一个模型属性,它执行连接并且具有where子句。
GameCompany(game_id, company_id, role)
答案 0 :(得分:2)
绝对可能。请阅读sqlalchemy
文档的Specifying Alternate Join Conditions部分,并附带示例代码。您的模型的代码可能如下所示:
class GameCompany(Base):
id = Column(Integer, primary_key=True)
company_id = Column(ForeignKey('games.id'))
# ...
class Games(Base):
__tablename__ = 'games'
id = Column(Integer, primary_key=True)
# ...
publishers = relationship(GameCompany,
primaryjoin=and_(GameCompany.game_id == id, GameCompany.role == 'publisher'))
developers = relationship(GameCompany,
primaryjoin=and_(GameCompany.game_id == id, GameCompany.role == 'developer'))