检测到SQLAlchemy循环依赖项

时间:2017-08-03 04:05:29

标签: sqlalchemy

我使用SQLAlchemy为我的应用程序创建了两个模型,但在使用它时我收到此错误消息:

 sqlalchemy.exc.CircularDependencyError: Circular dependency detected. (ProcessState(ManyToOneDP(PlayerModel.clan), <PlayerModel at 0x7f9503070ac8>, delete=False), ProcessState(ManyToOneDP(ClanModel.commander), <ClanModel at 0x7f95030b8da0>, delete=False), ProcessState(OneToManyDP(ClanModel.players), <ClanModel at 0x7f95030b8da0>, delete=False), SaveUpdateState(<PlayerModel at 0x7f9503070ac8>), SaveUpdateState(<ClanModel at 0x7f95030b8da0>), ProcessState(ManyToOneDP(ClanModel.owner), <ClanModel at 0x7f95030b8da0>, delete=False))

如何解决此错误?

class PlayerModel(Base):
    __tablename__ = 'player'

    chat_id = Column(Integer, primary_key=True)

    clan_id = Column(Integer, ForeignKey('clan.id'))
    clan = relationship("ClanModel", foreign_keys='PlayerModel.clan_id', back_populates="players", primaryjoin="PlayerModel.clan_id==ClanModel.id")

    def __repr__(self):
        return "<User(name='{}',level={})>".format(self.name, self.level)


class ClanModel(Base):
    __tablename__ = 'clan'

    id = Column(Integer, primary_key=True)
    war_with_id = Column(Integer, ForeignKey('clan.id'))
    war_with_from = relationship(
        'ClanModel',
        uselist=False,
        remote_side=[id],
        backref=backref('war_with_to', uselist=False),
    )

    owner_id = Column(Integer, ForeignKey('player.chat_id'))
    owner = relationship("PlayerModel", uselist=False, foreign_keys=owner_id)

    commander_id = Column(Integer, ForeignKey('player.chat_id'))
    commander = relationship("PlayerModel", uselist=False, foreign_keys=commander_id)

    players = relationship("PlayerModel", back_populates="clan", foreign_keys=PlayerModel.clan_id)

0 个答案:

没有答案