SQLAlchemy使用relationship()

时间:2013-03-06 02:36:01

标签: python database sqlalchemy relationship relational

我在这里使用SQLAlchemy,尝试制作几个表并链接它们并且在实现它时遇到了问题。

class Team(Base):

    __tablename__ = "teams"

    id = Column(Integer, primary_key=True)
    espn_team_id = Column(Integer, unique=True, nullable=False)
    games = relationship("Game", order_by="Game.date")

    def __init__(self, name):
        self.name = name
        self.espn_team_id = espn_team_id
        self.games = games

class Game(Base):
    __tablename__ = "games"

    id = Column(Integer, primary_key=True)
    espn_game_id=Column(Integer, unique=True, nullable=False)
    date = Column(Date)

    h_espn_id = Column(Integer, ForeignKey('teams.espn_team_id'))
    a_espn_id = Column(Integer, ForeignKey('teams.espn_team_id'))

我在一个用于创建表的文件中有这个。然后在另一个文件中,我使用insert()函数将值放入两个表中。我想如果我有一个拥有espn_team_id 360的团队,然后我将多个游戏放入游戏桌中,其中有h_espn_id = 360或a_espn_id = 360,我应该可以这样做:

a = Table("teams", metadata, autoload=True)
a = session.query(a).filter(a.c.espn_team_id==360).first().games 

它应该给我一个ID 360已经玩过的所有游戏团队的列表。但相反,我得到了这个错误

AttributeError:'NamedTuple'对象没有属性'games'

我在这里对SQLAlchemy或关系数据库有什么误解?

2 个答案:

答案 0 :(得分:1)

首先,您不必创建另一个Table对象,因为它可用作Team.__table__。无论如何,您只需查询映射的类,例如

query = Session.query(Team).filter(Team.espn_team_id == 360)
team360 = query.one()
games = team360.games

请参阅方法.one().first().all()的文档:http://docs.sqlalchemy.org/en/latest/orm/query.html

答案 1 :(得分:0)

这是我找到的解决方案,花了太长时间才明白这一点......

class Team(Base):

    __tablename__ = "teams"

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

    h_games = relationship(
                  "Game", 
                  primaryjoin="Game.h_espn_id==Team.espn_team_id", 
                  order_by="Game.date")
    a_games = relationship(
                  "Game", 
                  primaryjoin="Game.a_espn_id==Team.espn_team_id", 
                  order_by="Game.date")

    @hybrid_property
    def games(self):
        return self.h_games+self.a_games

    def __init__(self, name):
        self.name = name
        self.espn_team_id = espn_team_id
        self.h_games = h_games
        self.a_games = a_games
        self.games = games