SQLAlchemy映射器加入失败

时间:2011-03-24 17:49:52

标签: python postgresql join sqlalchemy

我有以下SQLAlchemy(0.6.6)代码:

class Player(object): pass
class Team(object): pass

players = Table('players', metadata, autoload=True)
teams = Table('teams', metadata, autoload=True)
players_teams = Table('players_teams', metadata, autoload=True)

mapper(Team, teams, properties={
      'players': relationship(Player, secondary=players_teams)
})

作为参考,我的表(postgresql 8.4)看起来像:

players
------------------
id   | primary key integer
name | varchar

teams
------------------
id   | primary key integer
name | varchar

players_teams
------------------
id        | primary key integer
player_id | foreign key references players (id)
team_id   | foreign key references teams(id)
signed    | datetime
released  | datetime

当我有Team类的实例时,我希望能够访问players属性并获取当前名单上的所有玩家。

sql应该类似于:

SELECT * FROM players p, teams t, players_teams pt
WHERE pt.player_id = p.id AND pt.team_id = t.id
AND pt.signed < now() AND pt.released is null

但是,根据SQLALchemy docs,我可以使用primaryjoin和secondaryjoin参数进一步深入了解联接。每当我这样做时,代码就会破坏各种堆栈跟踪。

如何更改此代码以使my_team.players返回所有当前玩家的列表,而不仅仅是所有玩家都在这个团队中?

0 个答案:

没有答案