prolods
prolods

Reputation: 37

Sqlalchemy: Self-referenced many-to-many InvalidRequestError

i have the following setup:

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))

As soon as i try to do:

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

or try to do the reference on the User class, i get the following error:

sqlalchemy.exc.InvalidRequestError: Table 'task' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

The table task is totally unrelated and just stores some values without any foreigen keys. For the full Stacktrace, see: https://pastebin.com/VijAtLqq

Cheers and thank you in advance prolods

Upvotes: 1

Views: 89

Answers (1)

prolods
prolods

Reputation: 37

Solved the problem, i deleted all relationships from the association table and added the following line to the User class.

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

Upvotes: 1

Related Questions