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?

1

1 Answer 1

4

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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.