SQLAlchemy:如何从祖父母那里获得孙子属性?

时间:2016-12-15 16:44:33

标签: python sql flask sqlalchemy flask-sqlalchemy

每个League都有很多季节,每个Season都有很多团队,每个Team表都有一个goals_for列。

假设我希望在所有赛季中计算一个联赛中所有goals_for个所有球队。但我仍然坚持在季节内访问球队。

以下内容返回League类型的项目:

get_teams_for_leagues = League.query.join(League.seasons).join(Season.teams).all()
print(get_teams_for_leagues)

如何从teams访问League

class League(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    full_name = db.Column(db.String, nullable=False)

    # One side of many to one with Season
    seasons = relationship("Season", back_populates="league", lazy='joined')

    def __repr__(self):
        return '<League %r>' % (self.full_name)

class Season(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    season_string_form = db.Column(db.String, nullable=False)

    # Many side of many to one wih Season
    league_id = db.Column(db.Integer, ForeignKey('league.id'))
    league = relationship("League", back_populates="seasons")

    # One side of many to one with Team
    teams = relationship("Team", back_populates="season")

    def __repr__(self):
        return '<Season %r>' % (self.id)


class Team(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    goals_for = db.Column(db.Integer, nullable=False)

    # Many side of many to one with Season
    season_id = db.Column(db.Integer, ForeignKey('season.id'))
    season = relationship("Season", back_populates="teams")

    def __repr__(self):
        return '<Team %r>' % (self.name)

1 个答案:

答案 0 :(得分:1)

可能只是进行聚合,例如:

from sqlalchemy.sql import func

res = db_session.query(func.sum(Team.goals_for), Team.name)\
         .join(Season).join(League)\
         .filter(League.full_name = 'La Liga')\
         .group_by(Team.name).all()