In Pydantic 2, when do you reach for field_serializer, model_serializer or computed_field to shape output, and what does each cost you?
answer
- one value, the whole model, a derived value
- plain replaces, wrap delegates
- handler argument
- readOnly in the output schema
basics
~10 sIn Pydantic 2, field_serializer changes how one field's value is written, model_serializer changes the whole model's output, and computed_field adds a property to the output. Each makes the dump differ from what validation accepts.
solid answer
~50 s`@field_serializer('field')` customises one field's output; in its default `'plain'` mode it replaces Pydantic's own serialization for that value, and in `'wrap'` mode it receives a `handler` that runs the standard logic so you can adjust before or after. `when_used` limits it to JSON output or skips `None`. `@model_serializer` does the same for the whole model: plain builds the output yourself, wrap calls `handler(self)` and edits the dict, for example to add an envelope. `@computed_field` on a property adds a derived value to every dump and to the serialization-mode JSON Schema as `readOnly`. The costs: a plain serializer's output is not checked against the field type, only one serializer per field or model is allowed, the output no longer matches what validation accepts, and every custom serializer is Python code on a path the core otherwise runs itself. They replace version 1's `json_encoders`, now deprecated.
code
python · 27 linesfrom datetime import datetime, timezone
from pydantic import BaseModel, computed_field, field_serializer
class ParcelShipped(BaseModel):
parcel_id: str
weight_grams: int
shipped_at: datetime
@computed_field
@property
def weight_kg(self) -> float:
return self.weight_grams / 1000
@field_serializer('shipped_at', when_used='json')
def as_epoch_seconds(self, value: datetime) -> int:
return int(value.timestamp())
evt = ParcelShipped(
parcel_id='p-9',
weight_grams=1250,
shipped_at=datetime(2026, 3, 1, tzinfo=timezone.utc),
)
print(evt.model_dump_json())
#> {"parcel_id":"p-9","weight_grams":1250,"shipped_at":1772323200,"weight_kg":1.25}go deeper
Recall the scopes: field_serializer for one field, model_serializer for the whole model, computed_field to add a derived property to the output.
Explain plain versus wrap and the handler, when_used, the info argument, and how a computed field appears in dumps and in the serialization-mode schema.
Weigh the costs: unchecked plain output, the one-serializer limit, divergence from what validation accepts, schema precision and per-value Python calls on hot paths.
Set a rule for where output shaping lives, reusable Annotated serializers for shared types and model serializers only at published boundaries, so payloads stay predictable across services.
## Three tools, three scopes Pydantic 2 lets you customise what a dump writes at three levels, and choosing the smallest one that fits keeps the rest of the model on its default, fast path: | Tool | Scope | Typical use | |---|---|---| | `@field_serializer` or an `Annotated` `PlainSerializer` / `WrapSerializer` | one field's value, or several named fields | a timestamp as epoch seconds, a money value as a string, masking a token | | `@model_serializer` | the whole model | an envelope around the payload, a flattened or renamed shape, a non-dict output | | `@computed_field` | adds a new key | a derived value such as a total or a display name | ## Field serializers A **field serializer** is a function that receives the field's value and returns what should be written. - **Plain mode** is the default for the decorator. It is called *instead of* Pydantic's own serialization for that field, and Pydantic does not check that your return value matches the field's type. - **Wrap mode** requires an extra `handler` argument. Calling `handler(value)` runs Pydantic's standard serialization, so you can transform the value before, or post-process the result after, or skip the handler entirely. - The `when_used` argument accepts `'always'` (the default), `'unless-none'`, `'json'` and `'json-unless-none'`. With `'json'`, `model_dump()` still returns the raw Python value while `model_dump_json()` and `mode='json'` use your function. - An optional `info` argument exposes the serialization mode (`info.mode` is `'python'` or `'json'`), the dump options such as `exclude_unset`, a user `context` passed to the dump call, and for field serializers the `field_name`. - A return annotation, or an explicit `return_type`, builds an extra serializer for the returned value and also shapes the serialization-mode JSON Schema. The decorator form can serve several fields at once, or `'*'` for every field, and `check_fields=False` lets a base class name fields that only subclasses define. The `Annotated` form is reusable: a type alias such as `EpochSeconds = Annotated[datetime, PlainSerializer(...)]` can be used across many models and inside `list[...]`. ## Model serializers `@model_serializer` works on the instance as a whole. In **plain** mode you build and return the whole output yourself, which may even be a non-dict value; in **wrap** mode you call `handler(self)` to get the standard dict and then add, remove or rename keys. Pydantic allows only **one serializer per field and one per model**, so you cannot stack a plain and a wrap serializer on the same target. ## Computed fields `@computed_field` applied to a `@property` (or a `functools.cached_property`) includes that property in `model_dump()`, `model_dump_json()` and the JSON Schema in serialization mode, where it is marked `readOnly`. Pydantic performs no validation, caching or invalidation on it; the property is plain Python. Two newer controls exist: the `exclude_computed_fields` dump option (2.12) drops all of them for one call, and the decorator's `exclude_if` argument (2.13) drops one conditionally. ## What each one costs 1. **Validation and output diverge.** A plain serializer that writes `"1.25 kg"` for a float field produces data the same model will refuse; a computed field writes a key the model has no field for. Round trips need care. 2. **No type safety on plain output.** Pydantic trusts what a plain serializer returns, so a bug can put any value on the wire. 3. **Schema drift.** The serialization-mode schema follows return annotations and computed fields, so an unannotated serializer can leave the published schema less precise than the payload. 4. **Speed.** Each custom serializer is a Python call per value on a path the core otherwise handles natively, which matters for large lists. 5. **One per target.** Combining behaviours means writing them into one function, or moving one part to a wrap serializer around the other's logic. ## Choosing quickly - Changing **how one type is written everywhere**: an `Annotated` alias with `PlainSerializer`, reused across models. - Changing **one field of one model**: `@field_serializer`, in wrap mode if the standard output only needs a small adjustment. - Changing **the shape of the whole payload**: `@model_serializer(mode='wrap')` at the boundary model only. - Adding **a derived value**: `@computed_field`, ideally on a cheap property or a `cached_property`. ## Where this replaced version 1 Pydantic 1 shaped output mainly through `json_encoders` in the model config, keyed by type. Version 2 added `field_serializer`, `model_serializer` and `computed_field` and deprecated `json_encoders`, citing its performance overhead and implementation complexity, so new code should use the decorators or the `Annotated` serializers.
- How does a serializer know whether it is producing Python output or JSON?Add an `info` parameter. `info.mode` is `'python'` or `'json'`, so one function can return a `Decimal` for Python callers and a string for JSON. If you only want the function in JSON output, `when_used='json'` is simpler: `model_dump()` then keeps the raw value without calling it.
- Why can a computed field break re-validation of a dumped payload?The dump contains a key such as `weight_kg` that is not a declared field. With the default `extra='ignore'` the model silently drops it on input; with `extra='forbid'` validation fails with `extra_forbidden`. Pass `exclude_computed_fields=True` (2.12) when the dump is meant to be read back, or relax the reading model.
- When would you prefer the Annotated PlainSerializer over the decorator?When the same output rule applies to a type across many models. `Annotated[datetime, PlainSerializer(...)]` becomes a reusable alias, can apply to list items, and is visible in the field annotation itself, whereas `@field_serializer` lives in one class but can cover several of its fields, or all of them with `'*'`.
- A plain field serializer's return value is validated against the field type
- You can stack a plain and a wrap serializer on the same field
- computed_field values are validated and cached by Pydantic
- json_encoders is still the recommended way to customise JSON output
- A field serializer's default mode is wrap, so the handler always runs
Assumes Pydantic 2; field_serializer, model_serializer and computed_field are new in version 2, which deprecated version 1's json_encoders config.