Base = declarative_base(metadata=metadata)


class TreeNode(Base):
    __tablename__ = 'tree'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('tree.id'))
name = Column(String(50), nullable=False)
children = relationship('TreeNode', cascade='all', backref=backref('parent',
    remote_side='TreeNode.id'), collection_class=
    attribute_mapped_collection('name'))

def __init__(self, name, parent=None):
    self.name = name
self.parent = parent

def append(self, nodename):
    self.children[nodename] = TreeNode(nodename, parent=self)

def __repr__(self):
    return 'TreeNode(name=%r, id=%r, parent_id=%r)' % (self.name, self.id,
        self.parent_id)
Создание дерева из самореферентных таблиц в SQLalchemy