model_dump() method for Python mode serialization
The model_dump() method converts Pydantic models to dictionaries in Python mode. By default, it preserves non-JSON serializable types (e.g., tuples remain as tuples). The method accepts a by_alias parameter: when by_alias=True, serialization uses field aliases instead of field names. It also accepts a mode parameter which can be set to 'json' to ensure JSON-compatible types are used in the output.
model_dump_json() method for JSON serialization
The model_dump_json() method serializes Pydantic models directly to a JSON-encoded string. It supports all types supported by the standard library json module plus many others (date/time types, UUID, sets, etc.). An indent parameter can be provided for pretty-printing. If an unsupported type is encountered, a PydanticSerializationError exception is raised.
Iterating over models yields field name and value pairs
Pydantic models can be iterated over, yielding (field_name, field_value) tuples. Field values are left as-is, so sub-models are not converted to dictionaries. Calling dict() on a model creates a dictionary using this iteration, but nested models remain as model instances rather than being recursively converted to dictionaries.
Pickling support for Pydantic models
Pydantic models support efficient pickling and unpickling using pickle.dumps() and pickle.loads(). Models can be serialized to pickled bytes and later deserialized back to model instances.
serialize_as_any runtime parameter
The serialize_as_any parameter can be passed to serialization methods like model_dump() and model_dump_json(). When set to True, Pydantic does not use type annotations to infer serialization; instead it inspects the actual runtime type of values. This applies to all nested types. When set to False (v2 default), fields present on subclasses but not base classes are not included.
Exclude and include parameters for serialization methods
Serialization methods like model_dump() accept exclude and include parameters. exclude accepts a set of field names or a dictionary structure specifying nested fields to exclude. include works similarly, specifying fields to include. For nested models, use dictionaries like {'user': {'username', 'password'}} or {'user': {0: True, -1: {'name'}}} for sequences. The special key '__all__' applies a pattern to all members in a sequence or dict.
exclude_defaults, exclude_none, and exclude_unset serialization parameters
Serialization methods accept three value-based exclusion parameters: exclude_defaults excludes fields whose value equals the default value, exclude_none excludes fields with None value, and exclude_unset excludes fields not explicitly set during instantiation (tracked by model_fields_set). These can be combined with exclude and include parameters.
Example of exclude parameter in model_dump()
```python
from pydantic import BaseModel, Field
class User(BaseModel):
id: int
username: str
class Transaction(BaseModel):
id: str
user: User
value: int
t = Transaction(
id='1234567890',
user=User(id=42, username='JohnDoe'),
value=9876543210,
)
print(t.model_dump(exclude={'user', 'value'}))
#> {'id': '1234567890'}
print(t.model_dump(exclude={'user': {'username'}, 'value': True}))
#> {'id': '1234567890', 'user': {'id': 42}}
```
This shows using exclude as a set to exclude top-level fields, and as a dictionary to exclude nested fields.
Example of exclude with sequence indexing
```python
from pydantic import BaseModel
class Hobby(BaseModel):
name: str
info: str
class User(BaseModel):
hobbies: list[Hobby]
user = User(
hobbies=[
Hobby(name='Programming', info='Writing code and stuff'),
Hobby(name='Gaming', info='Hell Yeah!!!'),
],
)
print(user.model_dump(exclude={'hobbies': {-1: {'info'}}}))
#> {'hobbies': [{'name': 'Programming', 'info': 'Writing code and stuff'}, {'name': 'Gaming'}]}
```
This shows using exclude with negative indexing to exclude the 'info' field from the last hobby.
Example of __all__ pattern in exclude
```python
from pydantic import BaseModel
class Hobby(BaseModel):
name: str
info: str
class User(BaseModel):
hobbies: list[Hobby]
user = User(
hobbies=[
Hobby(name='Programming', info='Writing code and stuff'),
Hobby(name='Gaming', info='Hell Yeah!!!'),
],
)
print(user.model_dump(exclude={'hobbies': {'__all__': {'info'}}}))
#> {'hobbies': [{'name': 'Programming'}, {'name': 'Gaming'}]}
```
This shows using the __all__ key to apply the exclusion pattern to all members in a sequence.
Example of exclude_unset parameter
```python
from pydantic import BaseModel
class UserModel(BaseModel):
name: str
age: int = 18
user = UserModel(name='John')
print(user.model_fields_set)
#> {'name'}
print(user.model_dump(exclude_unset=True))
#> {'name': 'John'}
user.age = 21
print(user.model_dump(exclude_unset=True))
#> {'name': 'John', 'age': 21}
```
This shows that exclude_unset excludes fields not explicitly provided during instantiation, and that modifying a field after creation adds it to the set of fields to serialize.
Example of serialize_as_any runtime parameter
```python
from pydantic import BaseModel
class User(BaseModel):
name: str
class UserLogin(User):
password: str
class OuterModel(BaseModel):
user1: User
user2: User
user = UserLogin(name='pydantic', password='password')
outer_model = OuterModel(user1=user, user2=user)
print(outer_model.model_dump(serialize_as_any=True))
#> {'user1': {'name': 'pydantic', 'password': 'password'}, 'user2': {'name': 'pydantic', 'password': 'password'}}
print(outer_model.model_dump(serialize_as_any=False))
#> {'user1': {'name': 'pydantic'}, 'user2': {'name': 'pydantic'}}
```
This shows how serialize_as_any at runtime applies to all fields, including multiple instances.