Skip to content

Functional Serializers

This module contains related classes and functions for serialization.

PlainSerializer dataclass

Plain serializers use a function to modify the output of serialization.

Attributes:

Name Type Description
func core_schema.SerializerFunction

The serializer function.

return_type Any

The return type for the function. If omitted it will be inferred from the type annotation.

when_used Literal['always', 'unless-none', 'json', 'json-unless-none']

Determines when this serializer should be used. Accepts a string with values 'always', 'unless-none', 'json', and 'json-unless-none'. Defaults to 'always'.

WrapSerializer dataclass

Wrap serializers receive the raw inputs along with a handler function that applies the standard serialization logic, and can modify the resulting value before returning it as the final output of serialization.

Attributes:

Name Type Description
func core_schema.WrapSerializerFunction

The serializer function to be wrapped.

return_type Any

The return type for the function. If omitted it will be inferred from the type annotation.

when_used Literal['always', 'unless-none', 'json', 'json-unless-none']

Determines when this serializer should be used. Accepts a string with values 'always', 'unless-none', 'json', and 'json-unless-none'. Defaults to 'always'.

field_serializer

field_serializer(
    *fields,
    mode="plain",
    return_type=PydanticUndefined,
    when_used="always",
    check_fields=None
)

Decorator that enables custom field serialization.

See Custom serializers for more information.

Four signatures are supported:

  • (self, value: Any, info: FieldSerializationInfo)
  • (self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)
  • (value: Any, info: SerializationInfo)
  • (value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)

Parameters:

Name Type Description Default
fields str

Which field(s) the method should be called on.

()
mode Literal['plain', 'wrap']

The serialization mode.

  • plain means the function will be called instead of the default serialization logic,
  • wrap means the function will be called with an argument to optionally call the default serialization logic.
'plain'
return_type Any

Optional return type for the function, if omitted it will be inferred from the type annotation.

PydanticUndefined
when_used Literal['always', 'unless-none', 'json', 'json-unless-none']

Determines the serializer will be used for serialization.

'always'
check_fields bool | None

Whether to check that the fields actually exist on the model.

None

Returns:

Type Description
Callable[[Any], Any]

The decorator function.

Source code in pydantic/functional_serializers.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def field_serializer(
    *fields: str,
    mode: Literal['plain', 'wrap'] = 'plain',
    return_type: Any = PydanticUndefined,
    when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always',
    check_fields: bool | None = None,
) -> Callable[[Any], Any]:
    """Decorator that enables custom field serialization.

    See [Custom serializers](../usage/serialization.md#custom-serializers) for more information.

    Four signatures are supported:

    - `(self, value: Any, info: FieldSerializationInfo)`
    - `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)`
    - `(value: Any, info: SerializationInfo)`
    - `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)`

    Args:
        fields: Which field(s) the method should be called on.
        mode: The serialization mode.

            - `plain` means the function will be called instead of the default serialization logic,
            - `wrap` means the function will be called with an argument to optionally call the
               default serialization logic.
        return_type: Optional return type for the function, if omitted it will be inferred from the type annotation.
        when_used: Determines the serializer will be used for serialization.
        check_fields: Whether to check that the fields actually exist on the model.

    Returns:
        The decorator function.
    """

    def dec(
        f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any]
    ) -> _decorators.PydanticDescriptorProxy[Any]:
        dec_info = _decorators.FieldSerializerDecoratorInfo(
            fields=fields,
            mode=mode,
            return_type=return_type,
            when_used=when_used,
            check_fields=check_fields,
        )
        return _decorators.PydanticDescriptorProxy(f, dec_info)

    return dec

model_serializer

model_serializer(
    __f=None,
    *,
    mode="plain",
    when_used="always",
    return_type=PydanticUndefined
)

Decorator that enables custom model serialization.

See Custom serializers for more information.

Parameters:

Name Type Description Default
__f Callable[..., Any] | None

The function to be decorated.

None
mode Literal['plain', 'wrap']

The serialization mode.

  • 'plain' means the function will be called instead of the default serialization logic
  • 'wrap' means the function will be called with an argument to optionally call the default serialization logic.
'plain'
when_used Literal['always', 'unless-none', 'json', 'json-unless-none']

Determines when this serializer should be used.

'always'
return_type Any

The return type for the function. If omitted it will be inferred from the type annotation.

PydanticUndefined

Returns:

Type Description
Callable[[Any], Any]

The decorator function.

Source code in pydantic/functional_serializers.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def model_serializer(
    __f: Callable[..., Any] | None = None,
    *,
    mode: Literal['plain', 'wrap'] = 'plain',
    when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always',
    return_type: Any = PydanticUndefined,
) -> Callable[[Any], Any]:
    """Decorator that enables custom model serialization.

    See [Custom serializers](../usage/serialization.md#custom-serializers) for more information.

    Args:
        __f: The function to be decorated.
        mode: The serialization mode.

            - `'plain'` means the function will be called instead of the default serialization logic
            - `'wrap'` means the function will be called with an argument to optionally call the default
                serialization logic.
        when_used: Determines when this serializer should be used.
        return_type: The return type for the function. If omitted it will be inferred from the type annotation.

    Returns:
        The decorator function.
    """

    def dec(f: Callable[..., Any]) -> _decorators.PydanticDescriptorProxy[Any]:
        dec_info = _decorators.ModelSerializerDecoratorInfo(mode=mode, return_type=return_type, when_used=when_used)
        return _decorators.PydanticDescriptorProxy(f, dec_info)

    if __f is None:
        return dec
    else:
        return dec(__f)  # type: ignore