如何将PostgreSQL LTREE的SQLAlchemy ORM字段转换为Pydantic模型/字符串
解决SQLAlchemy LtreeType转Pydantic模型的类型验证问题
问题根源是SQLAlchemy从数据库取出的path字段是Ltree实例,而Pydantic默认无法直接识别这个类型,导致model_validate时触发类型错误。以下是两种可行的解决方案:
方案一:自定义Pydantic类型
创建一个专门处理Ltree转换的Pydantic类型,同时支持接受Ltree对象或字符串输入,最终输出为字符串:
from pydantic import GetCoreSchemaHandler from pydantic_core import core_schema from sqlalchemy_utils.types.ltree import Ltree class PydanticLtree(str): @classmethod def __get_pydantic_core_schema__(cls, source_type: type, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: # 定义支持Ltree对象和字符串的联合schema,验证后转为字符串 return core_schema.no_info_after_validator_function( cls.validate, core_schema.union_schema([ core_schema.is_instance_schema(Ltree), core_schema.str_schema() ]) ) @classmethod def validate(cls, value): if isinstance(value, Ltree): return str(value) return value
然后在Pydantic模型中使用该类型:
from pydantic import BaseModel class Item(BaseModel): path: PydanticLtree # 其他业务字段...
方案二:使用字段级验证器
直接给Pydantic模型的path字段添加前置验证器,将Ltree对象转换为字符串:
from pydantic import BaseModel, BeforeValidator from sqlalchemy_utils.types.ltree import Ltree def convert_ltree_to_str(value): if isinstance(value, Ltree): return str(value) return value class Item(BaseModel): path: str = BeforeValidator(convert_ltree_to_str) # 其他业务字段...
两种方案都能让model_validate顺利将ORM模型的Ltree实例转换为Pydantic模型可接受的字符串类型,适配FastAPI的接口输出需求。如果需要支持反向转换(比如前端传字符串转Ltree存入数据库),可以在验证器中补充字符串转Ltree的逻辑。
内容的提问来源于stack exchange,提问作者Dmitri
相关产品推荐
相关产品推荐

