Например:
Код: Выделить всё
from typing import Annotated, Any
from pydantic import BaseModel, model_validator
from pydantic.functional_validators import ModelWrapValidatorHandler
from typing_extensions import Self
# Pretend this is some third-party class
# we can't modify directly...
class Quantity:
def __init__(self, value: float, unit: str):
self.value = value
self.unit = unit
class QuantityAnnotations(BaseModel):
value: float
unit: str
@model_validator(mode="wrap")
def _validate(value: Any, handler: ModelWrapValidatorHandler[Self]) -> Quantity:
if isinstance(value, Quantity):
return value
validated = handler(value)
if isinstance(validated, Quantity):
return validated
return Quantity(**dict(validated))
QuantityType = Annotated[Quantity, QuantityAnnotations]
class OurModel(BaseModel):
quantity: QuantityType = Quantity(value=0.0, unit='m')
Код: Выделить всё
model_instance = OurModel()
print(model_instance.model_dump_json())
# {"quantity":{"value":0.0,"unit":"m"}}
Код: Выделить всё
OurModel.model_json_schema()
# ...lib/python3.10/site-packages/pydantic/json_schema.py:2158: PydanticJsonSchemaWarning:
# Default value is not JSON serializable;
# excluding default from JSON schema [non-serializable-default]
Есть ли у кого-нибудь хороший обходной путь? легко включать аннотированные сторонние типы в качестве значений по умолчанию в схему JSON, созданную Pydantic?
Подробнее здесь: https://stackoverflow.com/questions/785 ... when-using