OrF*_*man 1 python validation decorator pydantic fastapi
我有一个 pydantic 类,例如:
from pydantic import BaseModel
class Programmer(BaseModel):
python_skill: float
stackoverflow_skill: float
total_score: float = None
Run Code Online (Sandbox Code Playgroud)
现在我正在根据其他字段计算 total_score:
@validator("total_score", always=True)
def calculat_total_score(cls, v, *, values):
return values.get("python_skill") + values.get("stackoverflow_skill")
Run Code Online (Sandbox Code Playgroud)
这很好用,但是现在当我更改其中一项技能时:
programmer = Programmer(python_skill=1.0, stackoverflow_skill=9.0)
print(programmer.total_score) # return 10.0
programmer.python_skill=2.0
print(programmer.total_score) # still return 10.0
Run Code Online (Sandbox Code Playgroud)
我希望 total_score 自动更新。
任何解决方案?TNX!!
您可以为此使用根验证器。每次更新后都会调用它。像这样:
from pydantic import BaseModel, validator, root_validator
class Programmer(BaseModel):
python_skill: float
stackoverflow_skill: float
total_score: float = None
class Config:
validate_assignment = True
@root_validator
def calculate_total_score(cls, values):
values["total_score"] = values.get("python_skill") + values.get("stackoverflow_skill")
return values
programmer = Programmer(python_skill=1.0, stackoverflow_skill=9.0)
print(programmer.total_score) # 10.0
programmer.python_skill = 2.0
print(programmer.total_score) # 11.0
Run Code Online (Sandbox Code Playgroud)
注意:1.7.3之前的版本有bug,建议更新
归档时间: |
|
查看次数: |
742 次 |
最近记录: |