How to delete a record by id in Flask-SQLAlchemy

PythonFlaskSqlalchemyFlask Sqlalchemy

Python Problem Overview


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

How can I delete some record by id?

Now I use the following code:

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

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

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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 shall works fine:

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

Solution 3 - Python

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()

Solution 4 - Python

In sqlalchemy 1.4 (2.0 style) you can do it like this:

from sqlalchemy import select, update, delete, values

sql1 = delete(User).where(User.id.in_([1, 2, 3]))
sql2 = delete(User).where(User.id == 1)

db.session.execute(sql1)
db.session.commit()

or

u = db.session.get(User, 1)
db.session.delete(u)
db.session.commit()

In my opinion using select, update, delete is more readable. Style comparison 1.0 vs 2.0 can be found here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergeyView Question on Stackoverflow
Solution 1 - PythonadarshView Answer on Stackoverflow
Solution 2 - PythonSteveView Answer on Stackoverflow
Solution 3 - PythonLogovsky DmitryView Answer on Stackoverflow
Solution 4 - PythonAbc XyzView Answer on Stackoverflow