Base.bind = engine


class Obj(Base):
    __table__ = sa.Table('objs', Base.metadata, sa.Column('id', sa.Integer,
        primary_key=True), sa.Column('parent_id', sa.Integer, sa.ForeignKey
        ('objs.id')), sa.Column('deleted', sa.Boolean))
children = orm.relationship('Obj', primaryjoin=sa.and_(orm.remote(__table__
    .c.parent_id) == __table__.c.id, orm.remote(__table__.c.deleted) ==
    False), backref=orm.backref('parent', remote_side=[__table__.c.id]),
    post_update=True)

def __repr__(self):
    return '<Obj id=%d children=%d>' % (self.id, len(self.children))
Исключить обратимо удаленные элементы в самореферентных отношениях SQLAlchemy