Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete model by primary key in SQLAlchemy

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.

like image 992
Eduard Luca Avatar asked Apr 29 '14 09:04

Eduard Luca


People also ask

How do I delete a SQLAlchemy model?

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

How do I delete a record by ID in flask SQLAlchemy?

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.

Does SQLAlchemy require primary key?

¶ 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.

What is primary key in flask SQLAlchemy?

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.


1 Answers

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()
like image 114
tuomur Avatar answered Sep 24 '22 17:09

tuomur