简体   繁体   中英

How to toggle boolean value in Pydantic (FastAPI)

EDIT: after @juanpa.arrivillaga correctly argued that the initial question did not provide a minimal reproductible example, I've decided to rewrite it adding more context: I'm using FastAPI.

I attempted to toogle an item value by defining a validator that would return the not of the item value:

from pydantic import BaseModel, Field, validator


class Foo(BaseModel):
    key: str = Field(...)
    condition: bool = Field(...)

    @validator('condition')
    def toogleCondition(cls, v):
        return not v

This toogle works .

However, when using the model in FastAPI it (apparently) didn't work.

from fastapi import FastAPI
from pydantic import BaseModel, Field, validator


# insert Foo definition here

app = FastAPI()


@app.get("/fail", response_model=Foo)
def fail():
    return Foo(key='hola', condition=True)


@app.get("/success")
def success():
    return Foo(key='hola', condition=True).dict()

If you run that code, you'll get that /fail toogles the value TWO TIMES, while /success toogles it only ONCE.

This is because response_model runs the validation AGAIN, which toogles it once more.

This normally works:

>>> import pydantic, typing
>>> data = [{'key': 'foo', 'condition': False}, {'key': 'bar', 'condition': True}]
>>> class Foo(pydantic.BaseModel):
...     key: str
...     condition: bool
...     @pydantic.validator("condition")
...     def toggle_condition(cls, v):
...         return not v
...
>>> class Bar(pydantic.BaseModel):
...     foo_list: typing.List[Foo]
...
>>> Bar(foo_list=data)
Bar(foo_list=[Foo(key='foo', condition=True), Foo(key='bar', condition=False)])
>>> data
[{'key': 'foo', 'condition': False}, {'key': 'bar', 'condition': True}]

Here's what I'm working with:

>>> pydantic.version.VERSION
'1.7.3'
>>> import sys
>>> print(sys.version)
3.7.7 (default, May  6 2020, 04:59:01)
[Clang 4.0.1 (tags/RELEASE_401/final)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM