“表”对象在SQLAlchemy关系上没有属性“ id”

时间:2019-03-07 15:34:08

标签: python sqlalchemy

我已经使用SQLAlchemy在三个单独的类之间建立了关系,并具有用于多对多关系的关联表。最小示例:

from sqlalchemy import *    
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import configure_mappers, relationship

Base = declarative_base()

teams_users = Table(
    'teams_users', Base.metadata,
    Column('team_id', ForeignKey('teams.id')),
    Column('user_id', ForeignKey('users.id'))
)

class User(Base):
    __tablename__ = 'users'
    # No autoincrement, since we're using externally-generated UIDs
    id = Column(Integer, primary_key=True, autoincrement=False)
    teams = relationship('Team', secondary=teams_users, back_populates="users")    

class Team(Base):
    __tablename__ = 'teams'
    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    game_id = Column(Integer, ForeignKey('games.id'), nullable=False)
    games = relationship("Game", foreign_keys='games.id')
    users = relationship("User", secondary='teams_users', back_populates="teams")

class Game(Base):
    __tablename__ = 'games'
    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    team1_id = Column(Integer, ForeignKey('teams.id'))
    team2_id = Column(Integer, ForeignKey('teams.id'))
    team1 = relationship("Team", back_populates="games", foreign_keys=team1_id, uselist=False)
    tean2 = relationship("Team", back_populates="games", foreign_keys=team2_id, uselist=False)

# done declaring, trigger the error
configure_mappers()

尝试查询这些关系中的任何一个都会返回'Table' object has no attribute 'id'错误:

Traceback (most recent call last):
  File "...", line 35, in <module>
    configure_mappers()
  File "/.../sqlalchemy/orm/mapper.py", line 3033, in configure_mappers
    mapper._post_configure_properties()
  File "/.../sqlalchemy/orm/mapper.py", line 1832, in _post_configure_properties
    prop.init()
  File "/.../sqlalchemy/orm/interfaces.py", line 183, in init
    self.do_init()
  File "/.../sqlalchemy/orm/relationships.py", line 1655, in do_init
    self._process_dependent_arguments()
  File "/.../sqlalchemy/orm/relationships.py", line 1680, in _process_dependent_arguments
    setattr(self, attr, attr_value())
  File "/.../sqlalchemy/ext/declarative/clsregistry.py", line 281, in __call__
    x = eval(self.arg, globals(), self._dict)
  File "<string>", line 1, in <module>
AttributeError: 'Table' object has no attribute 'id'

以这种方式构造它的目标是,我可以轻松地检查每个用户曾经加入过哪些团队。

此外,GameTeam中有两个外键,因为此项目的用例支持任意规模的团队,但仅支持两个团队。这使我获得了“ team1 won”的结果,并立即向获胜用户提供了统计跟踪和历史参考。

我在这里做什么错了?

1 个答案:

答案 0 :(得分:3)

要定义游戏和参与其中的两个团队之间的关系,您只需要给games表外键即可;一个团队可以进行多场比赛,一对多关系;完全删除games_id列。您得到的例外情况是,您会遇到一些麻烦,但无法在不需要该外键的关系中正确配置foreign_keys='games.id'参数。

Team类上的关系配置在这里有些棘手,因为Team.games属性必须与任一外键相关。 Handling Multiple Join Paths下的文档对此进行了介绍;您快到了,但是这里不需要uselist参数:

class Game(Base):
    __tablename__ = 'games'
    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    team1_id = Column(Integer, ForeignKey('teams.id'))
    team2_id = Column(Integer, ForeignKey('teams.id'))
    team1 = relationship("Team", foreign_keys=team1_id)
    team2 = relationship("Team", foreign_keys=team2_id)

请注意,我在这里省略了back_populates引用,因为两个关系更新另一个站点上的单个关系会导致两个外键中的一个或另一个被更新为另一个值,从而导致两个双方都是同一支球队!

逆关系属性Team.games需要自定义primaryjoin,因为您要寻找team1_idteam2_id是指向外键的游戏。使用foreign() annotation帮助SQLAlchemy确定何时更新关系(它将监视外键更改),并使用lambda推迟解析列:

class Team(Base):
    __tablename__ = 'teams'
    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    # game_id = Column(Integer, ForeignKey('games.c.id'), nullable=False)
    games = relationship(
        "Game",
        primaryjoin=lambda: or_(
            Team.id == foreign(Game.team1_id),
            Team.id == foreign(Game.team2_id)
        ),
        viewonly=True,
    )
    users = relationship("User", secondary='teams_users', back_populates="teams")

您还可以将primaryjoin做成一个包含现在正在lambda中执行的表达式的字符串,所以'or_(Team.id == foreign(Game.team1_id), Team.id == foreign(Game.team2_id))'

同样,没有back_populates,这种类型的关系不能自动更新已加载对象之间的关系。如果需要在提交之前看到这些关系的反映,则需要发出会话刷新。我还添加了viewonly=True,因为您无法将突变映射到Team.games列表中以更新数据库(将新游戏添加到列表中意味着该团队是团队1还是团队2) ?)。

您可能想要添加一个自定义约束表,以确保游戏永远不会在双方的同一支球队之间进行:

class Game(Base):
    # ...
    __table_args__ = (
        CheckConstraint(team1_id != team2_id, name='different_teams'),
    )

关系的快速演示:

from itertools import combinations

engine = create_engine('sqlite:///:memory:', echo=False)
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine)()

teams = [Team() for _ in range(3)]
session.add_all(teams)
user = User(id=42, teams=teams)
session.add(user)

games = [Game(team1=t1, team2=t2) for t1, t2 in combinations(teams, 2)]
session.add_all(games)
session.commit()

for team in user.teams:
    print('Team:', team.id, 'games:', [g.id for g in team.games])
for game in session.query(Game):
    print(f'Game {game.id}: team {game.team1.id} vs {game.team2.id}')

输出:

Team: 2 games: [1, 3]
Team: 1 games: [1, 2]
Team: 3 games: [2, 3]
Game 1: team 1 vs 2
Game 2: team 1 vs 3
Game 3: team 2 vs 3