假设我有一个
studen
t 模型,我想要的是:如果 age
< 6, make the school
可选。
我能做什么?预先感谢!
from pydantic import BaseModel
class Student(BaseModel):
name: str
age: int
school: str
student = Student(**{ "name": "Tom", "age": 10, "school": "Blabla"}) # validated
baby_student = Student(**{ "name": "Tom", "age": 5}) # expected to be validated
我尝试过的:
from pydantic import BaseModel, root_validator
class Student(BaseModel):
name: str
age: int
school: str
@root_validator(pre=True)
def ignore_school_if_baby(cls, values):
age = values.get("age")
if age < 6:
# don't know how to do here
values["school"] = None
return values
baby_student = Student(**{ "name": "Tom", "age": 5})
ValidationError: 1 validation error for Student
school
none is not an allowed value (type=type_error.none.not_allowed)
也尝试了以下方法,但仍然出现相同的错误
from typing import Optional
@root_validator(pre=True)
def ignore_school_if_baby(cls, values):
age = values.get("age")
if age < 6:
annotations = cls.__annotations__
annotations["school"] = Optional[annotations["school"]]
cls.__annotations__ = annotations
return values
from pydantic import BaseModel, root_validator
class Student(BaseModel):
name: str
age: int
school: str
@root_validator(pre=True)
def ignore_school_if_baby(cls, values):
age = values.get("age")
if age < 6:
cls.__fields__['school'].required = False
return values
baby_student = Student(**{ "name": "Tom", "age": 5})
我的笨蛋,我认为
cls.__fields__['school'].required = False
有效
您可以将
school
包裹成 Optional
类型。values["school"] = None
,school
将替换数据。,values["school"] = values.get("school")
可以避免这个问题。
class Student(BaseModel):
name: str
age: int
school: Optional[str]
@root_validator(pre=True)
def ignore_school_if_baby(cls, values):
age = values.get("age")
if age < 6:
values["school"] = values.get("school")
return values