[fix] Pydantic save json error

This commit is contained in:
Mark
2026-01-12 15:59:10 +08:00
parent 7a0746cf4e
commit f2390412d2
5 changed files with 105 additions and 22 deletions

25
api/app/base/type.py Normal file
View File

@@ -0,0 +1,25 @@
from pydantic import BaseModel, Field
from sqlalchemy import TypeDecorator, JSON
class PydanticType(TypeDecorator):
impl = JSON
def __init__(self, pydantic_model: type[BaseModel]):
super().__init__()
self.model = pydantic_model
def process_bind_param(self, value, dialect):
# 入库Model -> dict
if value is None:
return None
if isinstance(value, self.model):
return value.dict()
return value # 已经是 dict 也放行
def process_result_value(self, value, dialect):
# 出库dict -> Model
if value is None:
return None
# return self.model.parse_obj(value) # pydantic v1
return self.model.model_validate(value) # pydantic v2