我正在使用 pydantic v2,并且有一个 FutureAwareDatetime 的自定义架构。
class FutureAwareDatetime:
"""A datetime that requires timezone info and must be in the future."""
@classmethod
def __get_pydantic_core_schema__(
cls,
source: type[Any],
handler: GetCoreSchemaHandler,
) -> CoreSchema:
if cls is source:
# used directly as a type
return datetime_schema(
now_op="future",
tz_constraint="aware",
)
else:
schema = handler(source)
_check_annotated_type(schema["type"], "datetime", cls.__name__)
schema["now_op"] = "future"
schema["tz_constraint"] = "aware"
return schema
def __repr__(self) -> str:
return "FutureAwareDatetime"
虽然这工作正常,但当我使用例如序列化数据时,我希望能够使用 get
dt.isoformat(timespec="seconds")
model_dump()
我不想使用
field_serializer
装饰器,而是直接在类中使用它。
谢谢你。
搜索了一段时间后发现
datetime_schema()
有说法serialization
所以我添加了一个
PlainSerializer
。
我的代码看起来像
class FutureAwareDatetime:
"""A datetime that requires timezone info and must be in the future."""
@classmethod
def __get_pydantic_core_schema__(
cls,
source: type[Any],
handler: GetCoreSchemaHandler,
) -> CoreSchema:
serialize_to_iso8601 = PlainSerializer(
func=lambda dt: dt.isoformat(timespec="seconds"),
return_type=str,
)
if cls is source:
# used directly as a type
return datetime_schema(
now_op="future",
tz_constraint="aware",
serialization=serialize_to_iso8601,
)
else:
schema = handler(source)
_check_annotated_type(schema["type"], "datetime", cls.__name__)
return datetime_schema(
now_op="future",
tz_constraint="aware",
serialization=serialize_to_iso8601,
)