Why deleting non-existing record does not raise an error in sqlalchemy. no feedback on whether the record was deleted or not.
session.query(Element).filter(Element.id==ElementId).delete()
Thank you for your clarification.
Delete multiple rows in SQLAlchemyPass the delete query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results. The SQLAlchemy query shown in the below code deletes the “non-fiction” genre this will effectively delete multiple rows at one go.
Session. delete() marks an object for deletion, which will result in a DELETE statement emitted for each primary key affected.
How do I delete a record in SQLAlchemy? Python Flask and 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.
_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance. While not directly relevant to this section, if we want to get at it, we should use the inspect() function to access it).
I don't think it is an error. For example it is perfectly legal to issue a query to delete records in sql that "don't exist"
If i have a table 'posts' with a column 'id'. with no records
DELETE FROM posts WHERE ID > 0;
It is perfectly valid sql, there is no error, even though there are no rows
I am not too familiar with sqlalchmey but could you check to see if value exists first?
element = session.query(Element).filter(Element.id==ElementId).first()
if element:
# delete element
else:
# raise exception
The above will issue an additional query though...
Also, if you want a delete
method that raises error you can create your own session class
Change SQLAlchemy's Session.delete() behaviour
and override delete
As zzzeek points out delete
with a criteria
Returns the number of rows deleted, excluding any cascades.
Which is another option for seeing if any rows are deleted
Actually, sqlalchemy delete operation returns number of affected rows. So you can check and if affected rows is 0 then you can raise error.
effected_rows = session.query(Element).filter(Element.id==ElementId).delete()
if effected_rows == 0:
# raise exception
else:
# delete element
This works for me.
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