在SQLAlchemy中对连接的实体进行筛选和排序

时间:2016-02-29 13:54:20

标签: sqlalchemy filtering relationship

我有两个以一对多关系加入的课程(团队中的队员)。

我想查询具有特定职位的特定团队的所有玩家,并按照姓氏的顺序排序。

我的查询到目前为止看起来像这样:

query = db.session.query(Team).join(Player) \
    .filter(Team.team_id = team) \ #team is passed in to the function
    .filter(Player.position.in_(['QB', 'RB', 'WR', 'TE'])) \
    .order_by(Player.last_name).order_by(Player.first_name).first()

SQL会相应地生成,除非它缺少Player表的映射字段

SELECT team.team_id AS team_team_id, team.name AS team_name, team.city AS team_city, team.state AS team_state, team."stadiumName" AS "team_stadiumName" 
FROM team JOIN player ON team.team_id = player.team 
WHERE team.team_id = :team_id_1 AND player.position IN (:position_1, :position_2, :position_3, :position_4) ORDER BY player.last_name, player.first_name

如果我使用查询(Team,Player),我会得到元组。现在,它忽略了我在Player对象上的过滤器和orderby子句。我确定这是我失踪的一些小事。

根据以下建议,我尝试进行元组查询:

teams, players = db.session.query(Team, Player) \
    .filter(Team.team_id == team) \
    .filter(Player.position.in_(['QB', 'RB', 'WR', 'TE'])) \
    .order_by(Player.last_name).order_by(Player.first_name)

这导致

  

ValueError:解压缩的值太多(预期2)

1 个答案:

答案 0 :(得分:1)

执行单个往返结果的最简单方法是将两个实体放在查询中:

query = db.session.query(Team, Player).join(Player) \
    .filter(Team.team_id == team) \
    .filter(Player.position.in_(['QB', 'RB', 'WR', 'TE'])) \
    .order_by(Player.last_name).order_by(Player.first_name)

这会返回一个Team,Player元组列表,它们应与您的查询匹配。

获得顶级团队

team, p = query.first()

让玩家在查询中使用列表理解,如此

players=[player for _, player in query]
相关问题