Skip to content

API Reference

Pydantic

pydantic

Pydantic-backed JSON field for Tortoise ORM.

PydanticJSONField

Bases: JSONField[dict[str, object]]

JSONField that round-trips values through a Pydantic model.

On save, serializes BaseModel instances with model_dump(mode="json") before JSON encoding. On load, validates decoded data with the configured Pydantic model, including:

  • JSON strings or bytes (typical for SQLite).
  • Plain dicts returned by PostgreSQL JSONB drivers such as asyncpg.

Examples:

>>> class MyModel(Model):
...     data: PydanticJSONField[MyPydanticModel] = PydanticJSONField(
...         MyPydanticModel, default=MyPydanticModel
...     )
Source code in src/tortoise_extensions/pydantic.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class PydanticJSONField[T: BaseModel](JSONField[dict[str, object]]):
    """JSONField that round-trips values through a Pydantic model.

    On save, serializes ``BaseModel`` instances with ``model_dump(mode="json")``
    before JSON encoding. On load, validates decoded data with the configured
    Pydantic model, including:

    - JSON strings or bytes (typical for SQLite).
    - Plain dicts returned by PostgreSQL JSONB drivers such as asyncpg.

    Examples:
        >>> class MyModel(Model):
        ...     data: PydanticJSONField[MyPydanticModel] = PydanticJSONField(
        ...         MyPydanticModel, default=MyPydanticModel
        ...     )
    """

    def __init__(self, model_class: type[T], **kwargs: Any) -> None:
        """Initialize the field.

        Args:
            model_class: Pydantic model class used for validation.
            **kwargs: Additional arguments forwarded to ``JSONField``.
        """
        self._pydantic_model: type[T] = model_class
        super().__init__(**kwargs)

    @override
    def to_python_value(self, value: Any) -> T | None:  # pyright: ignore[reportExplicitAny, reportIncompatibleMethodOverride]
        """Convert a database value to a Pydantic model instance.

        Args:
            value: Raw value from the database driver.

        Returns:
            A validated Pydantic model, or ``None`` when the value is null.
        """
        if value is None:
            return None
        if isinstance(value, self._pydantic_model):
            return value
        if isinstance(value, (str, bytes)):
            raw = value if isinstance(value, str) else value.decode()
            return self._pydantic_model.model_validate_json(raw)
        return self._pydantic_model.model_validate(value)

    @override
    def to_db_value(self, value: Any, instance: type[Model] | Model) -> str | None:  # pyright: ignore[reportExplicitAny]
        """Convert a Python value to a JSON string for storage.

        Args:
            value: Model instance or JSON-serializable data.
            instance: Tortoise model class or instance (unused).

        Returns:
            Encoded JSON string, or ``None`` when the value is null.
        """
        if isinstance(value, BaseModel):
            value = value.model_dump(mode="json")
        return super().to_db_value(value, instance)
__init__(model_class: type[T], **kwargs: Any) -> None

Initialize the field.

Parameters:

Name Type Description Default
model_class type[T]

Pydantic model class used for validation.

required
**kwargs Any

Additional arguments forwarded to JSONField.

{}
Source code in src/tortoise_extensions/pydantic.py
29
30
31
32
33
34
35
36
37
def __init__(self, model_class: type[T], **kwargs: Any) -> None:
    """Initialize the field.

    Args:
        model_class: Pydantic model class used for validation.
        **kwargs: Additional arguments forwarded to ``JSONField``.
    """
    self._pydantic_model: type[T] = model_class
    super().__init__(**kwargs)
to_python_value(value: Any) -> T | None

Convert a database value to a Pydantic model instance.

Parameters:

Name Type Description Default
value Any

Raw value from the database driver.

required

Returns:

Type Description
T | None

A validated Pydantic model, or None when the value is null.

Source code in src/tortoise_extensions/pydantic.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@override
def to_python_value(self, value: Any) -> T | None:  # pyright: ignore[reportExplicitAny, reportIncompatibleMethodOverride]
    """Convert a database value to a Pydantic model instance.

    Args:
        value: Raw value from the database driver.

    Returns:
        A validated Pydantic model, or ``None`` when the value is null.
    """
    if value is None:
        return None
    if isinstance(value, self._pydantic_model):
        return value
    if isinstance(value, (str, bytes)):
        raw = value if isinstance(value, str) else value.decode()
        return self._pydantic_model.model_validate_json(raw)
    return self._pydantic_model.model_validate(value)
to_db_value(value: Any, instance: type[Model] | Model) -> str | None

Convert a Python value to a JSON string for storage.

Parameters:

Name Type Description Default
value Any

Model instance or JSON-serializable data.

required
instance type[Model] | Model

Tortoise model class or instance (unused).

required

Returns:

Type Description
str | None

Encoded JSON string, or None when the value is null.

Source code in src/tortoise_extensions/pydantic.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@override
def to_db_value(self, value: Any, instance: type[Model] | Model) -> str | None:  # pyright: ignore[reportExplicitAny]
    """Convert a Python value to a JSON string for storage.

    Args:
        value: Model instance or JSON-serializable data.
        instance: Tortoise model class or instance (unused).

    Returns:
        Encoded JSON string, or ``None`` when the value is null.
    """
    if isinstance(value, BaseModel):
        value = value.model_dump(mode="json")
    return super().to_db_value(value, instance)

UUID6

uuid6

UUID v6+ field for Tortoise ORM (via the uuid6 package).

FutureUUIDField

Bases: Field[UUID], UUID

UUID field compatible with UUID v6+ and the uuid6 package.

Stores UUIDs as CHAR(36) on most backends and as native UUID on PostgreSQL. When used as a primary key without an explicit default, assigns UUID7 via uuid6.uuid7.

Examples:

>>> class Item(Model):
...     id: FutureUUIDField = FutureUUIDField(primary_key=True)
...     class Meta:
...         table = "items"
Source code in src/tortoise_extensions/uuid6.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class FutureUUIDField(fields.Field[UUID], UUID):  # pyright: ignore[reportUnsafeMultipleInheritance]
    """UUID field compatible with UUID v6+ and the ``uuid6`` package.

    Stores UUIDs as ``CHAR(36)`` on most backends and as native ``UUID`` on
    PostgreSQL. When used as a primary key without an explicit ``default``,
    assigns UUID7 via ``uuid6.uuid7``.

    Examples:
        >>> class Item(Model):
        ...     id: FutureUUIDField = FutureUUIDField(primary_key=True)
        ...     class Meta:
        ...         table = "items"
    """

    SQL_TYPE = "CHAR(36)"

    class _db_postgres:
        SQL_TYPE = "UUID"

    def __init__(self, **kwargs: Any) -> None:  # pyright: ignore[reportExplicitAny]
        """Initialize the field.

        Args:
            **kwargs: Tortoise field options. Primary keys without ``default``
                receive ``uuid7`` automatically.
        """
        if kwargs.pop("pk", False):
            kwargs["primary_key"] = True
        if kwargs.get("primary_key") and "default" not in kwargs:
            kwargs["default"] = uuid7
        super().__init__(**kwargs)

    @override
    def to_db_value(self, value: Any, instance: type[Model] | Model) -> str | None:  # pyright: ignore[reportExplicitAny]
        """Convert a UUID to its string database representation.

        Args:
            value: UUID value or other supported input.
            instance: Tortoise model class or instance (unused).

        Returns:
            String UUID, or ``None`` when the value is falsy.
        """
        return value and str(value)

    @override
    def to_python_value(self, value: Any) -> UUID | None:  # pyright: ignore[reportExplicitAny]
        """Convert a database value to a ``uuid6.UUID`` instance.

        Args:
            value: Raw value from the database driver.

        Returns:
            Parsed UUID, or ``None`` when the value is null.
        """
        if value is None:
            return None
        if isinstance(value, UUID):
            return value
        return UUID(str(value))
__init__(**kwargs: Any) -> None

Initialize the field.

Parameters:

Name Type Description Default
**kwargs Any

Tortoise field options. Primary keys without default receive uuid7 automatically.

{}
Source code in src/tortoise_extensions/uuid6.py
31
32
33
34
35
36
37
38
39
40
41
42
def __init__(self, **kwargs: Any) -> None:  # pyright: ignore[reportExplicitAny]
    """Initialize the field.

    Args:
        **kwargs: Tortoise field options. Primary keys without ``default``
            receive ``uuid7`` automatically.
    """
    if kwargs.pop("pk", False):
        kwargs["primary_key"] = True
    if kwargs.get("primary_key") and "default" not in kwargs:
        kwargs["default"] = uuid7
    super().__init__(**kwargs)
to_db_value(value: Any, instance: type[Model] | Model) -> str | None

Convert a UUID to its string database representation.

Parameters:

Name Type Description Default
value Any

UUID value or other supported input.

required
instance type[Model] | Model

Tortoise model class or instance (unused).

required

Returns:

Type Description
str | None

String UUID, or None when the value is falsy.

Source code in src/tortoise_extensions/uuid6.py
44
45
46
47
48
49
50
51
52
53
54
55
@override
def to_db_value(self, value: Any, instance: type[Model] | Model) -> str | None:  # pyright: ignore[reportExplicitAny]
    """Convert a UUID to its string database representation.

    Args:
        value: UUID value or other supported input.
        instance: Tortoise model class or instance (unused).

    Returns:
        String UUID, or ``None`` when the value is falsy.
    """
    return value and str(value)
to_python_value(value: Any) -> UUID | None

Convert a database value to a uuid6.UUID instance.

Parameters:

Name Type Description Default
value Any

Raw value from the database driver.

required

Returns:

Type Description
UUID | None

Parsed UUID, or None when the value is null.

Source code in src/tortoise_extensions/uuid6.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@override
def to_python_value(self, value: Any) -> UUID | None:  # pyright: ignore[reportExplicitAny]
    """Convert a database value to a ``uuid6.UUID`` instance.

    Args:
        value: Raw value from the database driver.

    Returns:
        Parsed UUID, or ``None`` when the value is null.
    """
    if value is None:
        return None
    if isinstance(value, UUID):
        return value
    return UUID(str(value))