适配 Pydantic V2

This commit is contained in:
2024-05-06 07:38:57 +08:00
parent 42828f23f6
commit 42484b9c2c

View File

@@ -3,7 +3,7 @@ from datetime import datetime
from typing import Any from typing import Any
from nonebot.adapters import Message from nonebot.adapters import Message
from nonebot.compat import type_validate_json from nonebot.compat import PYDANTIC_V2, type_validate_json
from nonebot_plugin_orm import Model from nonebot_plugin_orm import Model
from pydantic import BaseModel, ValidationError from pydantic import BaseModel, ValidationError
from sqlalchemy import JSON, DateTime, Dialect, PickleType, String, TypeDecorator from sqlalchemy import JSON, DateTime, Dialect, PickleType, String, TypeDecorator
@@ -22,6 +22,16 @@ class PydanticType(TypeDecorator):
self.get_model = get_model self.get_model = get_model
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
if PYDANTIC_V2:
@override
def process_bind_param(self, value: Any | None, dialect: Dialect) -> str:
# 将 Pydantic 模型实例转换为 JSON
if isinstance(value, tuple(self.get_model())):
return value.model_dump_json(by_alias=True) # type: ignore[union-attr]
raise TypeError
else:
@override @override
def process_bind_param(self, value: Any | None, dialect: Dialect) -> str: def process_bind_param(self, value: Any | None, dialect: Dialect) -> str:
# 将 Pydantic 模型实例转换为 JSON # 将 Pydantic 模型实例转换为 JSON