Is it possible to delete a model (not sure that's what it's called in SQLAlchemy, I'm coming from Django) without actually querying and loading the full object in the session? Ie. something like this:
a = MyModel()
a.uid = 2 # this is the primary key
sess.delete(a)
This however throws an error: sqlalchemy.exc.InvalidRequestError: Instance '<MyModel at 0x7f69d112e210>' is not persisted
And I don't want to instance = session.query(MyModel).filter_by(uid=1).first()
and then delete
that, because I already have the IDs, I don't want to make useless queries.
query. filter(MyModel.id == 123). delete() More direct.
To delete a record by id in Python Flask-SQLAlchemy, we can call the session delete method. to call session. delete to mark obj1 and obj2 to be deleted. And then we call session.
¶ The SQLAlchemy ORM, in order to map to a particular table, needs there to be at least one column denoted as a primary key column; multiple-column, i.e. composite, primary keys are of course entirely feasible as well.
Most ORMs require that objects have some kind of primary key defined because the object in memory must correspond to a uniquely identifiable row in the database table; at the very least, this allows the object can be targeted for UPDATE and DELETE statements which will affect only that object's row and no other.
If you don't want to use raw SQL, the ORM queries can also delete objects:
session.query(MyModel).filter(MyModel.uid == 2).delete()
session.commit()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With