1

I encountered in a book some explanation how self referential tables in SQLAlchemy (Python) work, as an example, here is the class Employee with a manager_id:

class Employee(Base):
    __tablename__ = 'employees'
    id = Column(Integer(), primary_key=True)
    manager_id = Column(Integer(), ForeignKey('employees.id'))
    name = Column(String(255), nullable=False)
    manager = relationship("Employee", backref=backref('reports'),
    remote_side=[id])

unfortunately, I still don't really understand how this works.. In this case I guess every Employee can be a manager (with a manager_id) and Employee contains a reference to a manager, but what means backref=backref('reports') and what is reports? Is it another table? and what is remote_side=[id] in this case? does it reference to the employer.id, so to say that your manager manages some specific employer.id or the other way around, that each employer.id has some manager with a manager_id?

1
  • 1
    I know how the official docs are sometimes hard to get through or to find what you need => but for this case, the official SQL Alchemy docs have pretty good desc of this docs.sqlalchemy.org/en/13/orm/backref.html - especially they show you what is the EXACT EQUIVALENT if you would not use backref - that and the texts around it should answer all your questions :)
    – jave.web
    Jan 10, 2020 at 22:18

1 Answer 1

2

It just means that the inverted relation to "manager" is "reports" (an employee reports to a manager). The remote_side just says what column is used in the "remote" table (which is Employee again in this case) to establish the relationship.

1
  • ok and what does backref=backref("reports") mean in that case? Is it just a saved list reference to some "reports" list, where you can append the employees that report to some manager?
    – MarcL
    Nov 25, 2017 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.