如何获取 PydanticBaseSettingsSource 中的模型类型?

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

我正在编写一个自定义 PydanticBaseSettingsSource 并处理特定类型的字段

MyModel

class CustomSettingsSource(PydanticBaseSettingsSource):
    # Must implement
    def get_field_value(
        self, field: FieldInfo, field_name: str
    ) -> Tuple[Any, str, bool]:
        return ({}, "", False)

    def __call__(self) -> Dict[str, Any]:
        d: Dict[str, Any] = {}

        for field_name, field in self.settings_cls.model_fields.items():
            # If a field is of type MyModel I do custom processing/fetching
            
            # This returns <class 'mymodule.MyModel'>
            print(field.annotation)

            # This does not work
            if isinstance(field.annotation, MyModel):
                # do stuff...
        return d

我创建一个配置,分配 MyModel 类型的字段:

class Test(MyConfig):
    test: MyModel = MyModel(blah="sdfsdf")

正确的做法是什么?我真的不想做类似

if "MyModel" in str(field.annotation): ...
的事情,因为那感觉就像是黑客攻击。

python pydantic pydantic-v2
1个回答
0
投票

我发布作为答案,但我不确定它是否稳定或“正确”的迂腐方式来做到这一点。看起来这只是以字符串形式返回模型类型:

field.annotation.__qualname__

为什么会这样:

field.annotation.__class__

返回此:

<class 'pydantic._internal._model_construction.ModelMetaclass'>

但是

__qualname__
返回模型类名?我以前没有使用过
__qualname__
,这是本机 python 行为还是 pydantic 修改其模型类/字段的
__qualname__
属性以返回此非标准输出?

© www.soinside.com 2019 - 2024. All rights reserved.