Skip to content

Validation & Serialization

AMSDAL models inherit from Pydantic, giving you built-in data validation, type coercion, and serialization.

Type Validation

Fields are validated automatically on assignment:

from amsdal.models import Model

class Person(Model):
    name: str
    age: int

Person(name='John', age=25)       # OK
Person(name='John', age='not_a_number')  # ValidationError

Field Validators

Use @field_validator for custom validation logic:

from pydantic import field_validator
from amsdal.models import Model

class Person(Model):
    name: str
    age: int

    @field_validator('age')
    @classmethod
    def validate_age(cls, v: int) -> int:
        if v < 0 or v > 150:
            raise ValueError('Age must be between 0 and 150')
        return v

Model Validators

Use @model_validator to validate across multiple fields:

from pydantic import model_validator
from amsdal.models import Model

class DateRange(Model):
    start_date: str
    end_date: str

    @model_validator(mode='after')
    def validate_dates(self) -> 'DateRange':
        if self.start_date > self.end_date:
            raise ValueError('start_date must be before end_date')
        return self

Default Values

from amsdal.models import Model

class Settings(Model):
    theme: str = 'light'
    notifications: bool = True
    max_items: int = 50

Optional Fields

from amsdal.models import Model

class Person(Model):
    name: str
    nickname: str | None = None
    bio: str | None = None

Serialization

Convert model instances to dictionaries or JSON:

person = Person(name='John', age=25)

# To dict
person.model_dump()
# {'name': 'John', 'age': 25}

# To JSON string
person.model_dump_json()
# '{"name": "John", "age": 25}'

Models with References

For models with FK or M2M fields, serialization methods differ in how they handle related objects:

Method References
model_dump() Resolves — loads related objects and includes their data
model_dump_refs() Keeps as Reference — returns Reference dicts without loading
model_dump_json() Keeps as Reference — returns JSON with Reference dicts
class Car(Model):
    name: str
    owner: User  # FK field

car = Car(name='Ferrari', owner=user)

# Resolves references — includes full owner data
car.model_dump()
# {'name': 'Ferrari', 'owner': {'name': 'John', 'age': 25}}

# Keeps references — includes Reference dict
car.model_dump_refs()
# {'name': 'Ferrari', 'owner': {'ref': {'class_name': 'User', 'object_id': '...', ...}}}

Further Reading

For the full set of Pydantic features — custom types, complex validators, computed fields, JSON Schema generation, and more — see the Pydantic documentation.