How to filter with arbitrary amount of arguments in SQLModel?

35 Views Asked by At

I have a model with multiple attributes:

class HeroBase(SQLModel,BaseModel):
    id: int
    name: str
    secret_name: str
    age: int
    suit_color: str



class Hero(HeroBase, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    
class HeroFilter(HeroBase):
    id: Optional[int]
    name: Optional[str]
    secret_name: Optional[str]
    age: Optional[int]
    suit_color: Optional[str]
    

And I want to make request to filter this model that can accept arbitrary amount of attributes:

GET /heroes?name='batman'

GET /heroes?age=50&suit_color='red'

For example by iterating over inputed attributes:

@app.get('/heroes')
def get_heroes(filters: Annotated[HeroFilter, Depends()]):
    statement = select(Hero)
    for attr_name, attr_val in filters.model_dump().items():
         statement = statement.where(Hero[attr_name] == attr_val)
    return session.exec(statement).all() 

It throws error that model isn't a generator. Obviously. Is it a way I can pass attributes names by strings in where? Or any other method to make such requests?

0

There are 0 best solutions below