1

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?

Nath
  • 55
  • 1
  • 5
  • Use IN https://stackoverflow.com/questions/8603088/sqlalchemy-in-clause to fetch all matching data with a single query. – Ilja Everilä Jun 10 '20 at 15:22

1 Answers1

3

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()
marvls
  • 314
  • 2
  • 5