Skip to main content

Pydantic serialization for tortoise-orm

Project description

Tortoise Serializer

Motivation

This project was created to address some of the limitations of pydantic_model_creator, including:

  • The ability to use a context in serialization at the field level.
  • Access to the actual Tortoise Model instance during serialization.
  • Improved readability.
  • Support for adding extra logic to specific serializers.
  • The ability to document fields in a way that is visible in Swagger.

Installation

pip add tortoise-serializer

Core concept

A Serializer does not need to know which model it will serialize. For example:

from tortoise_serializer import Serializer


class ItemByNameSerializer(Serializer):
    id: int
    name: str


products = await ItemByNameSerializer.from_queryset(Product.all())
users = await ItemByNameSerializer.from_queryset(User.all())

This is entirely valid.

Serializers are pydantic.BaseModel objects, which means you can directly return them from FastAPI endpoints or use any functionality provided by BaseModel.

Usage

Reading

from tortoise_serializer import Serializer
from tortoise import Model, fields
from pydantic import Field
from fastapi.routing import APIRouter


class MyUser(Model):
    id = fields.IntegerField(primary_key=True)
    name = fields.CharField(max_length=100, unique=True)


class MyUserSerializer(Serializer):
    id: int
    name: str = Field(max_length=100, description="User unique name")


router = APIRouter(prefix="/users")


@router.get("")
async def get_users() -> list[MyUserSerializer]:
    return await MyUserSerializer.from_queryset(MyUser.all(), context={"user": ...})

(Note: You can specify a context to pass additional information to serializers, but it is not mandatory.)

Writing

from fastapi import Body
from pydantic import Field


class MyUserCreationSerializer(Serializer):
    name: str = Field(max_length=200)


@router.post("")
async def create_user(user_serializer: MyUserCreationSerializer = Body(...)) -> MyUserSerializer:
    user = await user_serializer.create_tortoise_instance(MyUser)
    # Here you can also pass a `context=` to this function.
    return await MyUserSerializer.from_tortoise_orm(user)

Note: It is currently not possible to handle ForeignKeys directly using serializers. You need to manage such logic in your views.

Context

The context in serializers is immutable.

Resolvers

Sometimes, you need to compute values or restrict access to sensitive data. This can be achieved with resolvers and context. Here's an example:

from tortoise_serializer import ContextType, Serializer, require_permission_or_unset
from tortoise import Model, fields


class UserModel(Model):
    id = fields.IntegerField(primary_key=True)
    address = fields.CharField(max_length=1000)


def is_self(instance: UserModel, context: ContextType) -> bool:
    current_user = context.get("user")
    if not current_user:
        return False
    return current_user.id == instance.id


class UserSerializer(Serializer):
    id: int
    # Default is set to None, but the field will be omitted.
    address: str | None = None

    @classmethod
    @require_permission_or_unset(is_self)
    async def resolve_address(cls, instance: UserModel, context: ContextType) -> str:
        return instance.address


@app.get("/users", response_model_exclude_unset=True)
async def list_users(user: UserModel = Depends(...)) -> list[UserSerializer]:
    return await UserSerializer.from_queryset(UserModel.all(), context={"user": user})

This ensures that the address field is not exposed to unauthorized users.

Async resolvers are called concurrently during serializer instantiation.

Relations

ForeignKeys & OneToOne

To serialize relations, declare a field in the serializer as another serializer:

from tortoise import Model, fields
from tortoise_serializer import Serializer


class BookShelf(Model):
    id = fields.IntField(primary_key=True)
    name = fields.CharField(unique=True)


class Book(Model):
    id = fields.IntField(primary_key=True)
    title = fields.CharField(db_index=True)
    shelf = fields.ForeignKeyField(
        "models.BookShelf",
        on_delete=fields.SET_NULL,
        null=True,
        related_name="books",
    )


class BookSerializer(Serializer):
    id: int
    title: str


class ShelfSerializer(Serializer):
    id: int
    name: str
    books: list[BookSerializer] = []


# Prefetching related fields is optional but improves performance.
serializer = ShelfSerializer.from_queryset(
    BookShelf.all().prefetch_related("books").order_by("name")
)

For a normal ForeignKey relationship:

class ShelfSerializer(Serializer):
    id: int
    name: str


class BookSerializer(Serializer):
    id: int
    title: str
    shelf: ShelfSerializer | None

Reverse relations are list[Serializer]

Limitations: Limitations: You cannot declare a field like this:

class SerializerA(Serializer):
    ...


class SerializerB(Serializer):
    ...


class MyWrongSerializer(Serializer):
    my_field = SerializerA | SerializerB

but you can still use None like:

class MySerializer(Serializer):
    some_relation: SerializerA | None = None

Many2Many

There are two ways to handle Many-to-Many relationships:

  • Use an intermediate Serializer with two ForeignKeys.
  • Use a resolver in the serializer.

Computed fields

Serialization involves resolving fields in the following order:

  • Resolvers (computed fields)
  • ForeignKeys
  • Model fields This order allows hiding fields based on the request.

Example of a computed field:

from pydantic import Field
from tortoise_serializer import Serializer, ContextType
from tortoise.queryset import QuerySet


class Book(Model):
    id = fields.IntField(primary_key=True)
    title = fields.CharField(db_index=True)
    shelf = fields.ForeignKeyField(
        "models.BookShelf",
        on_delete=fields.SET_NULL,
        null=True,
        related_name="books",
    )


class BookSerializer(Serializer):
    id: int
    title: str
    path: str
    # This description will appear in Swagger's schema.
    answer_to_the_question: int = Field(description="The answer to the big question of life")

    @classmethod
    async def resolve_path(cls, instance: Book, context: ContextType) -> str:
        if not instance.shelf:
            return instance.title
        if isinstance(instance.shelf, QuerySet):
            await instance.fetch_related("shelf")
        return f'{instance.shelf.name}/{instance.title}'

    @classmethod
    def resolve_answer_to_the_question(cls, instance: Book, context: ContextType) -> int:
        return 42

main_shelf = await Shelf.create(title="main")
my_book = await Book.create(title="Serializers 101", shelf=main_shelf)
serializer = await BookSerializer.from_tortoise_orm(my_book)

assert serializer.path == "main/Serializers 101"
assert serializer.answer_to_the_question == 42

All async resolvers will be resolved in concurency in a asyncio.gather, non-async ones will be resolved one after the other

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tortoise_serializer-1.0.2.tar.gz (7.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tortoise_serializer-1.0.2-py3-none-any.whl (8.5 kB view details)

Uploaded Python 3

File details

Details for the file tortoise_serializer-1.0.2.tar.gz.

File metadata

  • Download URL: tortoise_serializer-1.0.2.tar.gz
  • Upload date:
  • Size: 7.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.13.1 Linux/6.12.6-arch1-1

File hashes

Hashes for tortoise_serializer-1.0.2.tar.gz
Algorithm Hash digest
SHA256 a83ddd9d4c7f991f145555e057b8c796e635ce4b90f61d5453ce084a92d096df
MD5 3d55a1a8083fba94c0f5593b53c6114b
BLAKE2b-256 56cddb9fde9d15a54a6a54801dabf298c8670c4fe0668d03e1b21bf7feb36fa4

See more details on using hashes here.

File details

Details for the file tortoise_serializer-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: tortoise_serializer-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 8.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.13.1 Linux/6.12.6-arch1-1

File hashes

Hashes for tortoise_serializer-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 968793a51f5ac8adf59203002ab89c4a7b6edb2dca8a3e39f4fbbf69f7baba98
MD5 cbb7bbc1a263cc774558bc293db24ca1
BLAKE2b-256 2b0778cd82ab1f8771ecf829321caa026c768564a40f1be6e0eb35220e1b25d3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page