Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlalchemy delete subquery

I am trying to delete some child rows using a filtered query without result:

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

I am getting InvalidRequestError: Could not evaluate current criteria in Python. Specify 'fetch' or False for the synchronize_session parameter. as error.

Full stack trace:

Traceback (most recent call last):   File "/usr/src/tg2env/ceaf/ceaf/controllers/root.py", line 1673, in delete_local     DBSession.query(Servicio).filter(Servicio.puestos_id.in_(sl)).delete()   File "/usr/src/tg2env/lib/python2.4/site-packages/SQLAlchemy-0.6.6-py2.4.egg/sqlalchemy/orm/query.py", line 2126, in delete     raise sa_exc.InvalidRequestError( InvalidRequestError: Could not evaluate current criteria in Python.  Specify 'fetch' or False for the synchronize_session parameter. 

I am not be able to find where the problem is...

Any idea?

Regards

like image 699
LooPer Avatar asked Oct 25 '11 16:10

LooPer


People also ask

How do you bulk delete in SQLAlchemy?

Delete multiple rows in SQLAlchemy Get the books table from the Metadata object initialized while connecting to the database. Pass the delete query to the execute() function and get all the results using fetchall() function.

What is Synchronize_session false?

False - don't synchronize the session. This option is the most efficient and is reliable once the session is expired, which typically occurs after a commit(), or explicitly using expire_all().

What is subquery in SQLAlchemy?

The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.

What does all () do in SQLAlchemy?

all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present.


1 Answers

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.

like image 182
wberry Avatar answered Sep 21 '22 11:09

wberry