Yaakov Bressler
Yaakov Bressler

Reputation: 12098

SQLAlchemy delete a list of objects (opposite of bulk_save_objects)

If I want to save many objects within SQLAlchemy's ORM, I can use session.bulk_save_objects(). I want do the opposite of that --> I want to delete a list of objects all at once:

# Efficiently adding many objects:
obj_1 = Model(name="foo")
obj_2 = Model(name="bar")
session.bulk_save_objects([obj_1, obj_2])
session.commit() # execute


# How do I efficiently delete many objects?
record_obj = session.query(Model).filter(Model.name.in_(['foo', 'bar']).all()
# Assume `record_obj` is a list with a length of 2...


# CURRENT SOLUTION:
# I know I can loop through the list and delete them one by one, then commit
for obj in record_obj:
    session.delete(obj)
session.commit()


# DESIRED SOLUTION:
# Is it possible to delete the list itself?
session.delete(record_obj)

# Or maybe I need to unpack the list?
session.delete(*record_obj)

Upvotes: 2

Views: 4020

Answers (1)

Jelmer Wind
Jelmer Wind

Reputation: 429

As far as I can tell, SQLAlchemy does not provide such functionality out of the box. However, using you can get a fast delete in only a few lines:

obj_ids = [obj.id for obj in record_obj]
query = session.query(Model).filter(Model.id.in_(obj_ids))
query.delete(synchronize_session=False)
db.session.commit()

Where id should be replaced by the primary key in your model.

Upvotes: 1

Related Questions