Ayudh
Ayudh

Reputation: 1763

FastAPI in-memory filtering

I'm following the tutorial here: https://github.com/Jastor11/phresh-tutorial/tree/tutorial-part-11-marketplace-functionality-in-fastapi/backend/app and I had a question: I want to filter a model by different parameters so how would I do that?

The current situation is that I have a list of doctors and so I get all of them. Then depending on the filter query parameters, I filter doctors. I can't just do it all in one go because these query parameters are optional.

so I was thinking something like (psuedocode):

all_doctors = await self.db.fetch_all(query=GET_ALL_DOCTORS)

if language_id:
   all_doctors = all_doctors.filter(d => doctor.language_id = language_id)

if area:
   all_doctors = all_doctors.xyzabc

I'm trying out FastAPI according to that tutorial and couldn't figure out how to do this.

I have defined a model file for different models and am using SQLAlchemy.

One way I thought of is just getting the ids of all the doctors then at each filtering step, passing in the doctor ids from the last step and funneling them through different sql queries but this is filtering using the database and would result in one more query per filter parameter. I want to know how to use the ORM to filter in memory.

EDIT: So basically, in the tutorial I was following, no SQLAlchemy models were defined. The tutorial was using SQL statements. Anyways, to answer my own question: I would first need to define SQLAlchemy models before I can use them.

Upvotes: 1

Views: 2644

Answers (1)

MatsLindh
MatsLindh

Reputation: 52802

The SQLAlchemy query object (and its operations) returns itself, so you can keep building out the query conditionally inside if-statements:

query = db_session.query(Doctor)

if language_id:
    query = query.filter(Doctor.language_id == language_id)

if area_id:
    query = query.filter(Doctor.area_id == area_id)

return query.all()

The query doesn't run before you call all at the end. If neither argument is given, you'll get all the doctors.

Upvotes: 2

Related Questions