Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Serialization

Computed Fields and Custom Serializers

Add derived values to output with computed_field, change how a field is written with field_serializer, reshape whole models with model_serializer and use PlainSerializer.

Sometimes the data you store is not exactly what you want to send out. You may want a derived value (a full name built from two parts), a different format (a price in cents written as "12.50"), or a completely different shape. Pydantic offers four tools: @computed_field, @field_serializer, @model_serializer and PlainSerializer. Each changes only the output; validation is not affected.

computed_field: derived values

A normal @property is not included in dumps. Decorating it with @computed_field adds it to model_dump, model_dump_json and the JSON Schema, as a read-only field.

Python A computed field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The repr also shows computed fields. Because they are recomputed on every dump, they always reflect the current values. Computed fields are output only: sending area in the input is ignored (or rejected with extra="forbid").

field_serializer: change one field's output

@field_serializer("field_name") turns the value of a field into something else when dumping. By default it runs for both Python and JSON dumps; limit it with when_used.

Python field_serializer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

when_used takes "always" (default), "json", "json-unless-none" or "unless-none". Use "json" when you only want a special text format in JSON while keeping real objects in Python dumps.

A field serializer may also receive an info argument (SerializationInfo), which tells you what the caller asked for: info.mode, info.by_alias, info.exclude_none and more.

PlainSerializer: reusable output rules

If many fields need the same output format, attach the rule to a type with Annotated, just like constraints in Annotated Types:

Python A reusable serializer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Inside the program the values stay integers; only the output changes. WrapSerializer is the variant that receives a function to call the default serialization, for cases where you want to adjust rather than replace the result.

model_serializer: reshape the whole model

@model_serializer replaces the output of the entire model. The method returns whatever structure you like, such as a flat dict, a list or a string.

Python model_serializer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The result is a compact representation [[0.0, 0.0], [4.0, 0.0], [0.0, 3.0]]. In "wrap" mode (@model_serializer(mode="wrap")) your method receives a handler function that produces the normal dict, which you can then modify:

Python Wrap mode: adjust the default output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Which tool to pick

flowchart TD
    A["I want to change output"] --> B{"Add a value that is<br/>not stored?"}
    B -->|yes| C["@computed_field"]
    B -->|no| D{"Change one field<br/>only?"}
    D -->|"yes, once"| E["@field_serializer"]
    D -->|"yes, reusable"| F["Annotated + PlainSerializer"]
    D -->|no| G["@model_serializer"]

Start with the smallest tool that does the job.

Serializers change the output only. If you dump a model with a custom serializer and validate the result again, the data may not round-trip. A price written as "12.50 EUR" will not parse back into a Decimal. Keep a matching validator (Custom Validators later) if you need both directions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @computed_field do?

    A plain property is not part of the dump. computed_field adds it as an output-only field.
  2. 2. How do you apply a serialization rule to only the JSON output of a field?

    when_used controls whether the serializer runs for python dumps, JSON dumps, or both.
  3. 3. Which is best for the same output format applied to many fields in many models?

    An annotated type packages the rule once and reuses it anywhere.
  4. 4. In @model_serializer(mode='wrap'), what does handler(self) return?

    The handler runs the default serialization so you can adjust its result.

Summary

  • @computed_field on a property adds a derived, read-only value to dumps and schemas.
  • @field_serializer changes one field's output; when_used limits it to JSON or python dumps.
  • Annotated[T, PlainSerializer(...)] makes the rule reusable.
  • @model_serializer reshapes the whole model; mode="wrap" lets you adjust the default result.
  • Serializers affect output only, so plan a validator if you need to read the format back.

Next: JSON Schema Generation