Reputation: 65
I'm using Flask-SQLAlchemy and I have a few tables from a database.
I'm trying to select all the rows with a specific id, to run a function. Right now I'm doing it using an if statement like this:
IDs = [1,2,3,4]
for id in IDs:
data = Data.query.filter_by(id=id).first()
data.somefunction()
This does not seem very optimized, as I have to call the database for every id. I was wondering if there was a way to use Flask-SQLAlchemy to do a single query that returns all the rows from the database, and then I can run my function for every row and commit()
at the end?
Upvotes: 1
Views: 4052
Reputation: 334
IN:
DataResults = Data.query.filter(Data.id.in_(IDs)).all()
and for good measure, NOT IN:
DataResults = Data.query.filter(~Data.id.in_(IDs)).all()
Upvotes: 3