我想验证
pydantic
模型中的字段,该模型是另一个模型的子类。分配给该字段的类可以更改,但始终是该特定模型的子类。
考虑到模型的继承和子类定义,我收到了不应发生的错误。我认为这种情况不应该发生。我已在 github 存储库上报告了该错误。
我创建了一个 reprex,以便您可以直接看到错误:
from fastapi.datastructures import QueryParams
from pydantic import ConfigDict, Field, BaseModel
from humbldata.core.standard_models.abstract.humblobject import HumblObject
from humbldata.core.standard_models.toolbox import ToolboxQueryParams
from humbldata.core.standard_models.toolbox.technical.mandelbrot_channel import MandelbrotChannelQueryParams
class Model(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
command_params: QueryParams = Field()
# @field_validator("command_params")
# def validate_command_params(cls, v):
# if issubclass(type(v), QueryParams):
# return v
# raise TypeError("Wrong type for 'some_foo', must be subclass of Foo")
Model(command_params=MandelbrotChannelQueryParams())
我收到此错误:
---------------------------------------------------------------------------
ValidationError Traceback (most recent call last)
Cell In[23], line 19
10 command_params: QueryParams = Field()
12 # @field_validator("command_params")
13 # def validate_command_params(cls, v):
14 # if issubclass(type(v), QueryParams):
15 # return v
16 # raise TypeError("Wrong type for 'some_foo', must be subclass of Foo")
---> 19 Model(command_params=MandelbrotChannelQueryParams())
File c:\Users\jjfan\github\humblFINANCE-org\humbldata\menv\Lib\site-packages\pydantic\main.py:171, in BaseModel.__init__(self, **data)
169 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
170 __tracebackhide__ = True
--> 171 self.__pydantic_validator__.validate_python(data, self_instance=self)
ValidationError: 1 validation error for Model
command_params
Input should be an instance of QueryParams [type=is_instance_of, input_value=MandelbrotChannelQueryPar...False, live_price=False), input_type=MandelbrotChannelQueryParams]
For further information visit https://errors.pydantic.dev/2.6/v/is_instance_of
以下是答案的逻辑:
from pydantic import BaseModel, Field
from pydantic.config import ConfigDict
class QueryParams(BaseModel):
pass
class subQueryParams(QueryParams):
pass
class YourModel(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
command_params: QueryParams = Field()
YourModel(command_params=subQueryParams())
这是一个自定义验证器,如果您使用超类的前缀命名子类,则该验证器可以工作:
@field_validator("command_params")
def validate_command_params(cls, v):
class_name = v.__class__.__name__
if "QueryParams" in class_name:
return v
msg = "Wrong type for 'command_params', must be subclass of QueryParams"
raise TypeError(msg)