How to Delete Rows Using an SQLAlchemy Subquery
When trying to delete rows using an SQLAlchemy subquery, such as deleting all rows in Employee table where the age of associated Person is below 18, you might write code like this:
sl = DBSession.query(Person.id).filter(Person.age < 18).subquery()
DBSession.query(Employee).filter(Employee.person_id.in_(sl)).delete()
And after running it, you will got the following error:
sqlalchemy.exc.InvalidRequestError: Could not evaluate current criteria in Python:
"Cannot evaluate Select". Specify 'fetch' or False for the synchronize_session execution option.
The reason for this error is that SQLAlchemy cannot synchronize objects in a single loop when both SELECT and DELETE operations are involved.
To resolve it, you need to disable synchronization by adding the synchronize_session=False parameter:
sl = DBSession.query(Person.id).filter(Person.age < 18).subquery()
DBSession.query(Employee).filter(Employee.person_id.in_(sl)).delete(synchronize_session=False)
The issue’s StackOverflow Link
