Question

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.

Was it helpful?

Solution

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()

OTHER TIPS

Then, why you can't use session.execute like this

session.execute(
        "DELETE FROM mymodal WHERE uid=:param",
        {"param":2}
    )
session.flush()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top