Skip to main content

Field-Level Serialization Control

To control how individual fields are handled during serialization in this codebase, you configure the field's core schema definition—such as ModelField, TypedDictField, or DataclassField—with specific serialization attributes.

Renaming Fields with Aliases

You can change the key used for a field in the serialized output by setting a serialization alias. For most field types, use serialization_alias. For ComputedField, use alias.

from pydantic_core import SchemaSerializer, core_schema

# Renaming a field in a TypedDict
schema = core_schema.typed_dict_schema(
{
'internal_name': core_schema.typed_dict_field(
core_schema.str_schema(),
serialization_alias='external_name'
),
}
)

s = SchemaSerializer(schema)
assert s.to_python({'internal_name': 'hello'}) == {'external_name': 'hello'}

# Renaming a computed field
computed_schema = core_schema.model_schema(
cls=type('MyModel', (), {}),
schema=core_schema.model_fields_schema({
'a': core_schema.model_field(core_schema.int_schema())
}),
computed_fields=[
core_schema.computed_field(
property_name='get_val',
return_schema=core_schema.int_schema(),
alias='value'
)
]
)

Excluding Fields from Serialization

To permanently hide a field from the serialized output, set serialization_exclude=True. This is supported by ModelField, TypedDictField, and DataclassField.

# Found in pydantic-core/tests/serializers/test_typed_dict.py
s = SchemaSerializer(
core_schema.typed_dict_schema(
{
'visible': core_schema.typed_dict_field(core_schema.int_schema()),
'hidden': core_schema.typed_dict_field(
core_schema.int_schema(),
serialization_exclude=True
),
}
)
)

assert s.to_python({'visible': 1, 'hidden': 2}) == {'visible': 1}

Conditional Exclusion Based on Value

You can dynamically exclude a field based on its value at runtime using serialization_exclude_if. This parameter accepts a callable that receives the field's value and returns True if the field should be excluded.

# Found in pydantic-core/tests/serializers/test_model.py
class BasicModel:
def __init__(self, a, b):
self.a = a
self.b = b

s = SchemaSerializer(
core_schema.model_schema(
BasicModel,
core_schema.model_fields_schema(
{
# Exclude 'a' if it is greater than 1
'a': core_schema.model_field(
core_schema.int_schema(),
serialization_exclude_if=lambda x: x > 1
),
# Exclude 'b' if it contains 'foo'
'b': core_schema.model_field(
core_schema.str_schema(),
serialization_exclude_if=lambda x: 'foo' in x
),
}
),
)
)

assert s.to_python(BasicModel(a=0, b='bar')) == {'a': 0, 'b': 'bar'}
assert s.to_python(BasicModel(a=2, b='bar')) == {'b': 'bar'}
assert s.to_python(BasicModel(a=0, b='foobar')) == {'a': 0}

Configuring Dataclass Fields

DataclassField supports the same serialization controls as ModelField, allowing you to manage how standard Python dataclasses or Pydantic dataclasses are serialized.

# Found in pydantic-core/tests/serializers/test_dataclasses.py
s = SchemaSerializer(
core_schema.dataclass_schema(
type('MyDataclass', (), {}),
core_schema.dataclass_args_schema(
[
core_schema.dataclass_field(
name='a',
schema=core_schema.int_schema(),
serialization_alias='A'
),
core_schema.dataclass_field(
name='b',
schema=core_schema.int_schema(),
serialization_exclude_if=lambda x: x == 0
),
]
),
)
)

assert s.to_python(type('Inst', (), {'a': 1, 'b': 0})()) == {'A': 1}

Troubleshooting and Edge Cases

  • Alias Naming Consistency: While ModelField, TypedDictField, and DataclassField use the key serialization_alias, the ComputedField class uses the key alias.
  • Exclusion Precedence: If both serialization_exclude=True and serialization_exclude_if are provided, the field is excluded if either condition is met. For example, a field with serialization_exclude=True will never be serialized, regardless of the result of serialization_exclude_if.
  • Computed Fields and Round-tripping: By default, computed fields are excluded during "round-trip" serialization (where the output is intended to be loaded back into a model). They are also excluded if the global exclude_computed_fields flag is set on the serializer.