SqlAlchemy Entity类在加入时没有属性

时间:2016-02-22 22:55:21

标签: python postgresql join sqlalchemy

我正在尝试执行以下查询:

class PlayerMatchStats(Base):
    __tablename__ = 'players_stats'

    id = Column(Integer, primary_key=True)
    player_id = Column(ForeignKey('players.id'), index=True, nullable=False)
    player = relationship('Player', backref='stats')
    match_id = Column(ForeignKey('matches.id'), index=True, nullable=False)
    match = relationship('Match', backref='players_stats')
    team_id = Column(ForeignKey('teams.id'), index=True, nullable=False)
    team = relationship('Team', backref='players_matches_stats')


class Match(Base):
    __tablename__ = 'matches'

    id = Column(Integer, primary_key=True)
    league_id = Column(ForeignKey('leagues.id'), nullable=False, index=True)
    home_team_id = Column(ForeignKey('teams.id'), nullable=False, index=True)
    home_team = relationship('Team', foreign_keys=[home_team_id], backref='home_matches')
    away_team_id = Column(ForeignKey('teams.id'), nullable=False, index=True)
    away_team = relationship('Team', foreign_keys=[away_team_id], backref='away_matches')


class Player(Base):
    __tablename__ = 'players'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False, index=True)

这些是相关模型的一些部分:

Entity '<class 'model.overview.Match'>' has no property 'player'

尝试执行查询时,我收到的错误是:self.view.connect("row-activated", self.row_activated) def row_activated(self, widget, row, col): model = widget.get_model() print(model[row][:]) return True

1 个答案:

答案 0 :(得分:2)

当你真的需要过滤PlayerMatchStats的属性时,Sqlalchemy认为你正试图根据Match上的属性进行过滤。您可以使用“filter”方法而不是“filter_by”明确告诉SQLAlchemy您指的是哪个模型。总结:

stats = Session.query(PlayerMatchStats).join(Match, Match.id==PlayerMatchStats.match_id)\
    .filter(PlayerMatchStats.player=self).order_by(Match.date.desc()).limit(5).all()

这当然是假设“self”是一个Player对象