Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy is there a way to Returning result after Delete execution

I can't find equivalent solution about Returning clause

DELETE FROM items
WHERE sub_item_id IN %(sub_item_ids)s
RETURNING item_id, sub_item_id, 

I did this in SQLAlchemy :

purge_family = session.query(ItemItem).filter(ItemItem.sub_item_id.in_(sub_item_ids))

.delete(synchronize_session=False)

I need to return item_id, sub_item_id set upon execution of DELETE statement.

like image 957
Anouar Mokhtari Avatar asked Jun 26 '17 12:06

Anouar Mokhtari


People also ask

How to delete multiple rows at once in SQLAlchemy?

Pass the delete query to the execute () function and get all the results using fetchall () function. Use a for loop to iterate through the results. The SQLAlchemy query shown in the below code deletes the “non-fiction” genre this will effectively delete multiple rows at one go.

How do I delete a table in SQL alchemy?

from sqlalchemy import delete Tablename.delete ().where (Tablename.c.column_name == value) 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. Use a for loop to iterate through the results.

How to get the value of a deleted row in SQL?

For DELETE, the values are those of the rows which were deleted. Upon execution, the values of the columns to be returned are made available via the result set and can be iterated using CursorResult.fetchone()and similar.

What happened to the UPDATE statement in SQLAlchemy?

The rendered UPDATE statement will emit the SET clause for each referenced column maintaining this order. Deprecated since version 1.4: The update.preserve_parameter_orderparameter will be removed in SQLAlchemy 2.0. Use the Update.ordered_values()method with a list of tuples. New in version 1.0.10. See also


1 Answers

To execute your query as is use Core constructs:

stmt = ItemItem.__table__.delete().\
    where(ItemItem.sub_item_id.in_(sub_item_ids)).\
    returning(ItemItem.item_id, ItemItem.sub_item_ids)

results = session.execute(stmt).fetchall()
like image 172
Ilja Everilä Avatar answered Oct 11 '22 03:10

Ilja Everilä