SQL Alchemy - How to delete a model instance?
Asked Answered
M

3

26

Say I have a model instance like this:

instance = session.query(MyModel).filter_by(id=1).first()

How can I delete that row? Is there a special method to call?

Mcintire answered 23/7, 2010 at 21:3 Comment(1)
Remember to use .get(1) instead of filter_by(id=1).first(), if 'id' is the primary key! This results in less database hits. Read: docs.sqlalchemy.org/en/latest/orm/…Mesozoic
M
45

Ok I found it after further searching:

session.delete(instance)
Mcintire answered 23/7, 2010 at 22:11 Comment(2)
I think this is better if you delete by id: MyModel.query.filter(MyModel.id == 123).delete() More direct. See #27159073Paralytic
I don't know about the original usecase behind this question but regardless, deleting with an id is not "better" or "more direct" in itself. It is just one of several options to get the job done. -- If I already have an instance, because I had to use it for other reasons, then it is clearly more direct to use session.delete(instance) rather than session.query(InstanceModel).filter_by(a=instance.a, ...).delete() (typical relation model).Nauseate
L
17

You can fire a Single query for this.

For all records:

session.query(MyModel).delete()
session.commit()

It will delete all records from it and if you want to delete specific records then try filter clause in the query. ex.

For specific value:

session.query(MyModel).filter(MyModel.id==1).delete()
session.commit()
Lordling answered 7/3, 2018 at 9:24 Comment(1)
I am getting sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got '<class '__main__.ModelName'>'.Annulet
M
0

For me, it's working with delete and commit:

session.delete(instance)
session.commit()
Mccready answered 28/6, 2024 at 15:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.