from sqlalchemy.orm import Query from pydantic import BaseModel from fastapi import…
- User
from sqlalchemy.orm import Query from pydantic import BaseModel from fastapi import HTTPException class FilterParams(BaseModel): seq: int = None # type: ignore code: str = None # type: ignore desc: str = None # type: ignore
@case_status_router.post("/items/filtering") async def case_filtering(filter_params: FilterParams, db: Session = Depends(get_db)): try: query: Query = db.query(model_case_status) for column_name, column_value in filter_params.dict().items(): if column_value is not None: query = query.filter(getattr(model_case_status, column_name) == column_value) items = query.all() return {"items": items} except Exception as e: raise HTTPException(status_code=500, detail=str(e))
- Assistant
As an AI language model, I cannot run this code since I don't have access to a database.
The code above defines a function to filter items in a database table based on given filter parameters. The database session is accessed through a dependency function
get_db. TheFilterParamsclass defined using Pydantic base model specifies the available filter parameters with default values ofNone.The
case_filteringfunction takes the filter parameters as input and applies them to the query by filtering the model attributes based on column names and values provided in the request. The filtered items are returned as a response. If there is an exception while executing the query, an HTTPException with 500 status code is raised with the error message. - User
this code cannot accpet mutil input on same field? e.g. : 'PDF', 'PRC' on code field
- Assistant
The current implementation of the
case_filteringfunction can only handle a single input value for each field. If you want to search for multiple items in the same field, you can modify theFilterParamsclass to accept a list of values for the input parameters:codeclass FilterParams(BaseModel): seq: List[int] = None code: List[str] = None desc: List[str] = NoneWith this change, you can pass a list of values in the request payload to filter the items on the same field:
code{ "seq": [1, 2, 3], "code": ["PDF", "PRC"], "desc": ["Description 1", "Description 2"] }Then, in the
case_filteringfunction, you can modify the loop to iterate through the list of values in the filter params and use thein_()method to filter the query:codefor column_name, column_values in filter_params.dict().items(): if column_values is not None: query = query.filter(getattr(model_case_status, column_name).in_(column_values))