SQLAlchemy – Mapping self-referential relationship as one to many (declarative form)

You add a ForeignKey referencing the parent, and then create a relationship that specifies the direction via remote_side. This is documented under adjacency list relationships. For declarative you’d do something like this:

class Tag(Base):
    __tablename__ = 'tag'

    id = Column(Integer, primary_key=True)
    label = Column(String)
    parent_id = Column(Integer, ForeignKey('tag.id'))

    parent = relationship('Tag', remote_side=[id])

If you want the reverse relation also, add backref="children" to the relationship definition.

Leave a Comment