在sqlalchemy中两次反向引用同一个名称

2024-10-02 00:19:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的数据库模式中有匹配项和团队,一个团队有一个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])

这是我得到的错误:

^{pr2}$

解决这个问题的最佳方法是什么?为什么存在这种局限性?在


Tags: idbasecolumninteger团队teamclassfirst
1条回答
网友
1楼 · 发布于 2024-10-02 00:19:52

有一个限制,因为任何对象最多只能有一个同名的属性或方法。在

但是,您可以执行以下操作:

  1. 使用两个不同的名字
  2. 创建第三个,以便在需要检查所有匹配项时使用。这里可以使用简单的@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],
    )

下面的测试代码现在应该可以工作了:

^{pr2}$

相关问题 更多 >

    热门问题