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
| Name | Type | Description |
|---|---|---|
| field | str | The first field name the serializer should apply to; must be a string. |
| *fields | str | Additional field names the serializer should apply to. |
| mode | Literal['plain', 'wrap'] = 'plain' | The serialization mode: 'plain' replaces default logic entirely, while 'wrap' provides a handler to optionally invoke default serialization. |
| return_type | Any = PydanticUndefined | Optional return type for the function; if omitted, it is inferred from the decorated function's type annotation. |
| when_used | WhenUsed = 'always' | Determines the conditions under which the serializer is active (e.g., always, only for JSON, or only for Python objects). |
| check_fields | `bool | None` = None |
Returns
| Type | Description |
|---|---|
Callable | A decorator function that wraps the serializer method and registers it with the Pydantic model's serialization logic. |