1

我在这里使用 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”对象没有属性“游戏”

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

4

2 回答 2

1

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

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

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

于 2013-03-06T05:36:10.777 回答
0

Here is the solution I found, took way too long to understand this...

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
于 2013-03-10T16:23:45.640 回答