如何使所有字段具有以别名名的名称?

问题描述 投票:0回答:0
创建我的模型可选。

I创建的功能以获取基类注释。 def get_annotations(main_cls): ret_val = main_cls.__annotations__ for base_cls in main_cls.__bases__: if base_cls != BaseModel: ret_val.update(get_annotations(base_cls)) return ret_val

创建可选模型AS

OptionalClientModel = create_model( "OptionalClientModel", **{k: (Optional[v], None) for k, v in get_annotations(ClientModel).items()})
原始课程如下

from typing import Annotated from bson import ObjectId from pydantic import Field from pydantic import EmailStr from pydantic import BaseModel from pydantic import ConfigDict from pydantic import AwareDatetime from pydantic import field_validator # Represents an ObjectId field in the database. # It will be represented as a `str` on the model so that it can # be serialized to JSON. PyObjectId = Annotated[str, BeforeValidator(str)] class DBTableBase(BaseModel): # The primary key for the Table, stored as a `str` on the instance. # This will be aliased to `_id` when sent to MongoDB, # but provided as `id` in the API requests and responses. id: PyObjectId | None = Field(alias="_id", serialization_alias="id", default=None) model_config = ConfigDict( json_encoders={ObjectId: str}, json_schema_extra={ "example": { "id": "BSON_ID" } }, ) class ClientModel(DBTableBase): first_name: str last_name: str
当我想要具有所有可选值的型号时,我可以使用

OptionalClientModel

问题是,
id

没有任何Alia。

如何与别名创建可选?
    

OptionalClientModel

这应该满足您的需求。无需自己迭代注释。
    
	

python mongodb alias pydantic
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.