How to delete a record by id in Flask-SQLAlchemy
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction
--
Chapters
00:00 Question
00:45 Accepted answer (Score 333)
01:06 Answer 2 (Score 90)
01:28 Answer 3 (Score 23)
02:05 Answer 4 (Score 20)
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/2715...
Answer 1 links:
http://docs.sqlalchemy.org/en/latest/orm...
Answer 2 links:
[here]: https://docs.sqlalchemy.org/en/14/change...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #flask #sqlalchemy #flasksqlalchemy
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction
--
Chapters
00:00 Question
00:45 Accepted answer (Score 333)
01:06 Answer 2 (Score 90)
01:28 Answer 3 (Score 23)
02:05 Answer 4 (Score 20)
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/2715...
Answer 1 links:
http://docs.sqlalchemy.org/en/latest/orm...
Answer 2 links:
[here]: https://docs.sqlalchemy.org/en/14/change...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #flask #sqlalchemy #flasksqlalchemy
#avk47
ACCEPTED ANSWER
Score 356
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.
ANSWER 2
Score 98
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()
ANSWER 3
Score 33
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.
ANSWER 4
Score 20
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()