Python + SQLAlchemy: delete using Session object

I cannot fully understand this: I would like to delete all records from the table by the corresponding query. A 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 does not work. What is the idea here? Error:

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

+4
source share
1 answer

In SQL Alchemy, you delete the objects that you receive with the query from the database. There are two ways to do this:

Deletion using a query (it produces only one statement DELETE):

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

Removing an instance of the object returned by the request (gives 2 statements: first SELECT, then DELETE):

obj=session.query(User).filter(User.id==7).first()
session.delete(obj)
session.commit()
+9
source

All Articles