2

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Interesting! You can perform a query and execute query.delete()! That's clever.
Yes you can! Note that the in_() part of the query may get very slow if you have many (>1000) items. In that case, instead of providing an explicit list, it may be better to write a query to find the items.
@JelmerWind could you explain better what you mean by "it may be better to write a query to find the items"? In plain SQL if we do a select or a delete the IN statement should be equal in terms of performance, they should use the same index or table access, shouldn't they?
Suppose you want to remove all Models for which Model.model_class_id = 1, then it may be faster to write: query = session.query(Model).filter(Model.model_class_id == 1).delete() In practice, this filter could be a lot more complex, including joins with other tables etc. In my experience, this is faster weather there is an index on model_class_id or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.