Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python + SQLAlchemy: deleting with the Session object

I can't quite figure this out: I'd like to delete all the records from a table on a matching query. Kind of like this.

engine = sqlalchemy.create_engine(string) meta = MetaData(bind=engine) meta.reflect(bind=engine, schema='myschema')  Base = automap_base(metadata=meta) Base.prepare(engine, reflect=True) Classes = Base.classes  Session = sessionmaker(bind=engine) session = Session()  session.delete(plays.record_id == '123') 

But that isn't working. What's the idea here? Error I get is:

error in parsing record ID 020087: Class 'sqlalchemy.sql.elements.BinaryExpression' is not mapped

like image 813
Wells Avatar asked Oct 30 '14 01:10

Wells


People also ask

What function from the Session object is used to delete items in SQLAlchemy?

delete() is invoked upon an object and the Session is flushed, the row is deleted from the database.

How do I delete a record in SQLAlchemy ORM?

It is easy to perform delete operation on a single table. All you have to do is to delete an object of the mapped class from a session and commit the action.

How do I delete a SQLAlchemy model?

query. filter(MyModel.id == 123). delete() More direct.

What does Session flush do SQLAlchemy?

session. flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.


2 Answers

In SQL Alchemy you are deleting Objects that you get with a query from the database. This you can do in 2 Ways:

Deleting with query (will issue just one DELETE statement):

session.query(User).filter(User.id==7).delete() session.commit() 

Deleting object instance returned by a query (will issue 2 statements: first SELECT, then DELETE):

obj=session.query(User).filter(User.id==7).first() session.delete(obj) session.commit() 
like image 70
muthan Avatar answered Sep 22 '22 17:09

muthan



Delete All Records

#for all records session.query(Model).delete() session.commit() 

Deleted Single Row

If you want to delete specific records then try filter clause in the query. ex.

#for specific value session.query(Model).filter(Model.id==123).delete() session.commit() 

Delete Single Record by Object

record_obj = session.query(Model).filter(Model.id==123).first() session.delete(record_obj) session.commit() 

https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records

like image 43
Anand Tripathi Avatar answered Sep 23 '22 17:09

Anand Tripathi