'pydantic string 'false' to bool

I have pydantic model like

class AccountingQueueFilters(BaseModel):
    no_batch_id: Optional[bool] = None

but for input 'false' from get params it return True

https://mysite.tech/accounting_queue/get?no_batch_id=false

How to fix ?



Solution 1:[1]

You should use this construction It will allow you to access properties via dot notation and make custom type checks

class QueryParams:
    def make_bool(self, value):
        return not(value == "false")  # some logic

    def __init__(self, boolable: str, zero: bool):
        self.boolable = self.make_bool(boolable)
        self.zero = zero


@router.get('/route')
async def route(
        data: QueryParams = Depends(),
):
    print(data) # boolable=false : str
    print(type(data.boolable))  # bool
    print("success")
    return Result(data)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eugene Lavrentyev