Sqlalchemy delete subquery

Solution 1:

After looking in the source where your exception occurs I suggest trying this:

sl = DBSession.query(Puesto.id).filter(Puesto.locales_id == id).subquery()
DBSession.query(Servicio).filter(Servicio.puestos_id.in_(sl)) \
.delete(synchronize_session='fetch')

See the documentation of the delete method for what this means. Passing the fetch argument will basically run the query twice, once as a select and once as a delete.

If running two queries is not desired, pass synchronize_session=False instead and then call session.expire_all() immediately after the delete to avoid having inconsistent state within the MetaData store.