26

Say I get 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?

Greg
  • 45,306
  • 89
  • 231
  • 297
  • 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: http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.get – MrEbbinghaus Jan 13 '17 at 17:19

2 Answers2

43

Ok I found it after further searching:

session.delete(instance)
Greg
  • 45,306
  • 89
  • 231
  • 297
  • 2
    I think this is better if you delete by id: MyModel.query.filter(MyModel.id == 123).delete() More direct. See https://stackoverflow.com/questions/27158573/how-to-delete-a-record-by-id-in-flask-sqlalchemy – Sergiy Migdalskiy Jun 11 '17 at 21:04
  • 2
    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). – Romain Vincent May 30 '20 at 13:24
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()
bfontaine
  • 18,169
  • 13
  • 73
  • 107
Anand Tripathi
  • 14,556
  • 1
  • 47
  • 52
  • I am getting `sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got ''`. – saadi Jul 12 '20 at 11:50