I'm trying to delete a list of items from using Flask and SQLAchlemy in an elegant way. In my case, I want to delete old items (items that are less than a certain time are considered old) from my database.
Here is my python model object:
class ItemModel(db.Model):
__tablename__ = 'items'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
time = db.Column(db.Integer)
Now, I tried to delete the items using the following filter_by query:
def delete_from_db(self):
db.session.query('items').filter_by(self.time <= epoch_time).delete()
db.session.commit()
It just ends up giving me the error:
filter_by() takes 1 positional argument but 2 were given
If I try this using the filter function, instead of filter_by, I also receive an error:
def delete_from_db(self):
db.session.query('items').filter(self.time <= epoch_time).delete()
db.session.commit()
sqlalchemy.exc.InvalidRequestError: This operation requires only one Table or entity be specified as the target.
Finally, I decide to go back to the basics and use sql code and this works but I don't think it is very elegant:
def delete_from_db(self):
from sqlalchemy.sql import text
cmd = 'delete from items where time <= :time'
db.engine.execute(text(cmd), time = epoch_time)
db.session.commit()
Is there a more elegant way to do this with Flask and SQLAchlemy?
Delete multiple rows in SQLAlchemyGet the books table from the Metadata object initialized while connecting to the database. Pass the delete query to the execute() function and get all the results using fetchall() function.
Session. delete() marks an object for deletion, which will result in a DELETE statement emitted for each primary key affected.
method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.
session. flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.
This should work with a class method if you want to manage this from the model :
@classmethod
def delete_from_db(cls):
cls.query.filter(cls.time <= epoch_time).delete()
db.session.commit()
or the same, maybe cleaner, with a static method :
@staticmethod
def delete_from_db():
ItemModel.query.filter(ItemModel.time <= epoch_time).delete()
db.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