How to delete a record by id in Flask-SQLAlchemy How to delete a record by id in Flask-SQLAlchemy python python

How to delete a record by id in Flask-SQLAlchemy


You can do this,

User.query.filter_by(id=123).delete()

or

User.query.filter(User.id == 123).delete()

Make sure to commit for delete() to take effect.


Just want to share another option:

# mark two objects to be deletedsession.delete(obj1)session.delete(obj2)# commit (or flush)session.commit()

http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting

In this example, the following codes shall works fine:

obj = User.query.filter_by(id=123).one()session.delete(obj)session.commit()


Another possible solution specially if you want batch delete

deleted_objects = User.__table__.delete().where(User.id.in_([1, 2, 3]))session.execute(deleted_objects)session.commit()