Clone wiki

sqlalchemy / UsageRecipes / DeclarativeSelfReferencingTable

The following example shows how to create a self-referencing table using Declarative:

class Location(Base):
        __tablename__ = 'location'
        parent_id = Column(Integer, ForeignKey(''))
        parent = relation('Location', backref=backref('children'), remote_side='')
        name = Column(String(80), unique=True)

Each record can reference a parent record of type Location. A ".children" backref allows you to access the list of all children.