Skip to main content

field_serializer

Decorator that enables custom field serialization.

def field_serializer(
field: str,
*fields: str,
mode: Literal['plain', 'wrap'] = 'plain',
return_type: Any = PydanticUndefined,
when_used: WhenUsed = 'always',
check_fields: bool | None = None
) - > Callable

Decorator that enables custom field serialization. Use this to define how specific model fields should be converted during serialization, such as transforming a set into a sorted list.

Parameters

NameTypeDescription
fieldstrThe first field name the serializer should apply to; must be a string.
*fieldsstrAdditional field names the serializer should apply to.
modeLiteral['plain', 'wrap'] = 'plain'The serialization mode: 'plain' replaces default logic entirely, while 'wrap' provides a handler to optionally invoke default serialization.
return_typeAny = PydanticUndefinedOptional return type for the function; if omitted, it is inferred from the decorated function's type annotation.
when_usedWhenUsed = 'always'Determines the conditions under which the serializer is active (e.g., always, only for JSON, or only for Python objects).
check_fields`boolNone` = None

Returns

TypeDescription
CallableA decorator function that wraps the serializer method and registers it with the Pydantic model's serialization logic.