How to delete record by id in Flask-SQLAlchemy

I have a users table in my MySql database. This table has the fields id , name and age .

How can I delete an entry using id ?

Now I use the following code:

 user = User.query.get(id) db.session.delete(user) db.session.commit() 

But I do not want to make any requests before the delete operation. Is there any way to do this? I know that I can use db.engine.execute("delete from users where id=...") , but I would like to use the delete() method.

+97
python flask flask-sqlalchemy sqlalchemy
Nov 26 '14 at 8:45
source share
3 answers

You can do it,

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

or

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

commit sure that delete() takes effect.

+164
Nov 26 '14 at 21:35
source share

Just want to share another option:

 # mark two objects to be deleted session.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 should work fine:

 obj = User.query.filter_by(id=123).one() session.delete(obj) session.commit() 
+20
Aug 22 '17 at 15:39
source share

Another possible solution, especially if you want batch removal

 deleted_objects = User.__table__.delete().where(User.id.in_([1, 2, 3])) session.execute(deleted_objects) session.commit() 
+2
Mar 14 '19 at 12:47
source share



All Articles