pydantic:如果提交的 B 符合某些条件,则将提交的 A 设为可选

问题描述 投票:0回答:2

假设我有一个

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
python pydantic
2个回答
0
投票
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
有效


0
投票

您可以将

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
© www.soinside.com 2019 - 2024. All rights reserved.