Sqlalchemy:自引用多对多InvalidRequestError

时间:2018-07-09 12:09:31

标签: python-3.x sqlalchemy

我具有以下设置:

class User(Base):
    __tablename__ = 'user'
    id = Column("id", Integer, primary_key=True)


class SupervisorUserAssociation(Base):

    def __init__(self, supervisor, empolyee):
        self.supervisor = supervisor
        self.empolyee = empolyee

    __tablename__ = 'supervisoruserassociation'
    id = Column(Integer, primary_key=True, autoincrement=True)
    supervisorId = Column('supervisor',Integer,ForeignKey('user.id'))
    supervisor = relationship(User,backref="supervisors",primaryjoin=(User.id == supervisorId))
    employeeId = Column('employee',Integer,ForeignKey('user.id'))
    employee = relationship(User,backref="employees",primaryjoin=(User.id == employeeId))

我尝试做的事情:

 employee = relationship(User,backref="employees",primaryjoin=(User.c.id == employeeId))

或尝试在User类上进行引用,我得到以下错误:

  

sqlalchemy.exc.InvalidRequestError:表“任务”已定义   此MetaData实例。将'extend_existing = True'指定为   重新定义现有Table对象上的选项和列。

表任务是完全不相关的,只是存储一些值而没有任何前兆键。 有关完整的Stacktrace,请参阅:https://pastebin.com/VijAtLqq

干杯,谢谢你 闹着

1 个答案:

答案 0 :(得分:0)

解决了该问题,我从关联表中删除了所有关系,并将以下行添加到User类。

supervisors = relationship("User",
                           secondary=SupervisorUserAssociation.__table__,
                           primaryjoin="User.id == SupervisorUserAssociation.employeeId",
                           secondaryjoin="User.id == SupervisorUserAssociation.supervisorId",backref="employees")