如何通过代码获取 pydantic 模型的定义的某个字段的 max_length 取值?-灵析社区

编程界菜niao

如何通过代码获取 pydantic 模型的定义的某个字段的 max_length 取值? 比如获取 description 的 max_length 的值 class MetaCollection(BaseModel): id: int | None = Field(default=None) collection_name: str = Field(max_length=64) description: str | None = Field(None, max_length=1024) meta_type: MetaType = Field() company_id: int = Field(...) default_selected: bool = Field(default=False) meta_count: int = Field(default=0, help_text='去正常化设计') timer_count: int = Field(default=0, help_text='去正常化设计') chatGPT 的回答,我跑了一下不行 > 你可以使用 Python 的 `get_field` 方法来访问 Pydantic 模型字段的元数据,包括 > `max_length`。在你的情况下,你可以这样做: > > > from pydantic import BaseModel, Field > > class MetaCollection(BaseModel): > id: int | None = Field(default=None) > collection_name: str = Field(max_length=64) > description: str | None = Field(None, max_length=1024) > # ... 其他字段 > > # 获取 description 字段的 max_length > description_max_length = > MetaCollection.__fields__["description"].field_info.extra["max_length"] > print(description_max_length) > > 这段代码中,`MetaCollection.__fields__["description"]` 可以访问到 `description` > 字段的元数据,然后通过 `.field_info.extra["max_length"]` 来获取 `max_length` 的值。 > > 记得替换 `MetaCollection` 为你实际定义的模型名称,以及替换字段名如果你想获取其他字段的 `max_length`。 会报错 Traceback (most recent call last): File "/home/pon/Desktop/code/me/ideaboom/001.py", line 10, in description_max_length = MetaCollection.__fields__["description"].field_info.extra["max_length"] KeyError: 'max_length'

阅读量:20

点赞量:0

问AI
解决了 下面是 pydantic v1 中的用法 在 Pydantic 中,max_length 是存储在 field_info 对象的 max_length 属性中的,而不是 extra 字典中。 from pydantic import BaseModel, Field class MetaCollection(BaseModel): id: int | None = Field(default=None) collection_name: str = Field(max_length=64) description: str | None = Field(None, max_length=1024) # ... 其他字段 # 获取 description 字段的 max_length description_max_length = MetaCollection.__fields__["description"].field_info.max_length print(description_max_length) 至于 pydantic v2 版本下如何获取,我去提问了:"https://github.com/pydantic/pydantic/discussions/8388" (https://link.segmentfault.com/?enc=LSzPygkZ7bvzKhksf2Jw0A%3D%3D.0ARZK9KyaMD9XKVw%2F7xNduXL4dPkiKUcRdHRfC3Rg8DBAC3VxLfi8%2FiUTSN%2Fg7M66EwAHG8TJoifttTBt9WflQ%3D%3D)