1. Michael Bayer
  2. sqlalchemy

Wiki

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('location.id'))
        parent = relation('Location', backref=backref('children'), remote_side='location.c.id')
        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.

Updated