在我的数据库架构中,有匹配和团队,团队有first_opponent
和second_opponent
。现在,每个都应该作为团队的反向引用。作为第一或第二对手没有真正的区别,因此反向引用应该具有相同的名称。但是,我不能简单地创建两个具有相同名称的反向引用。
这是我的表格定义(简化形式):
class Team(Base):
__tablename__ = "teams"
id = Column(Integer, primary_key=True)
name = Column(String)
class Match(Base):
__tablename__ = "matches"
id = Column(Integer, primary_key=True)
first_opponent_id = Column(Integer, ForeignKey("teams.id"))
second_opponent_id = Column(Integer, ForeignKey("teams.id"))
first_opponent = relationship("Team", backref=backref('matches'), foreign_keys=[first_opponent_id])
second_opponent = relationship("Team", backref=backref('matches'), foreign_keys=[second_opponent_id])
这是我得到的错误:
sqlalchemy.exc.ArgumentError: Error creating backref 'matches' on relationship 'Match.second_opponent': property of that name exists on mapper 'Mapper|Team|teams'
解决这个问题的最佳方法是什么?为什么存在这种限制?
答案 0 :(得分:4)
存在一个限制,因为任何对象都可以拥有最多一个具有相同名称的属性或方法。
但您可以执行以下操作:
@property
代码:
class Team(Base):
__tablename__ = "teams"
id = Column(Integer, primary_key=True)
name = Column(String)
@property
def matches(self):
return self.matches_to + self.matches_from
class Match(Base):
__tablename__ = "matches"
id = Column(Integer, primary_key=True)
first_opponent_id = Column(Integer, ForeignKey("teams.id"))
second_opponent_id = Column(Integer, ForeignKey("teams.id"))
first_opponent = relationship(
"Team", backref=backref('matches_to'),
foreign_keys=[first_opponent_id],
)
second_opponent = relationship(
"Team", backref=backref('matches_from'),
foreign_keys=[second_opponent_id],
)
以下测试代码现在应该可以使用:
t1, t2, t3 = Team(name='uno'), Team(name='due'), Team(name='tre')
m1 = Match(first_opponent=t1, second_opponent=t2)
m2 = Match(first_opponent=t1, second_opponent=t3)
m3 = Match(first_opponent=t2, second_opponent=t3)
assert 2 == len(t1.matches)
assert 2 == len(t2.matches)
assert 2 == len(t3.matches)
session.add_all([t1, t2, t3])
session.commit()
assert 2 == len(t1.matches)