Overview

Pydantic 2.1, released on August 18, 2023, improves computed fields and adds new serialization options.

Main Features

Improved computed fields

The @computed_field decorator now better supports JSON serialization and inclusion in the JSON schema.

python
from pydantic import BaseModel, computed_field

class Product(BaseModel):
    price: float
    tax_rate: float = 0.20

    @computed_field
    @property
    def total(self) -> float:
        return round(self.price * (1 + self.tax_rate), 2)

Serialization options

The mode parameter in model_dump lets you choose between Python and JSON serialization.

python
from pydantic import BaseModel
from datetime import datetime

class Event(BaseModel):
    name: str
    date: datetime

e = Event(name='Conf', date=datetime(2023, 8, 18))
print(e.model_dump(mode='json'))
# {'name': 'Conf', 'date': '2023-08-18T00:00:00'}

Sources