如何通过代码获取 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'