Skip to content

Quickstart

This tutorial builds a small blog backend on an in-memory SQLite database: two related models, Author and Post, and every core Ferro operation: create, query, traverse a relationship, update, delete and run a transaction.

Every code block comes from one runnable script, shown in full under Complete script. To follow along in a file of your own, start with these imports:

import asyncio

from ferro import connect, engines, transaction

The model block comes next at module level. Every block after it uses await, so it goes inside one async def main() that you run with asyncio.run(main()), in the order the page shows them; the script has that shape. You can also run the script as it is.

Models

Ferro supports two equivalent field-declaration styles: options on the assignment side, or inside typing.Annotated. Every model example in these docs shows both, so pick one and stay consistent in your project. Declare the two models:

from datetime import UTC, datetime

from ferro import Field, Forward, Model, Relation, Reverse


class Author(Model):
    id: int | None = Field(default=None, primary_key=True)
    name: str
    email: str = Field(unique=True)

    posts: Relation[list["Post"]] = Reverse("author_id")


class Post(Model):
    id: int | None = Field(default=None, primary_key=True)
    title: str
    body: str
    published: bool = False
    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    author_id: int = Field(foreign_key=Author)

    author: Relation[Author] = Forward("author_id")
from datetime import UTC, datetime
from typing import Annotated

from ferro import Field, Forward, Model, Relation, Reverse


class Author(Model):
    id: Annotated[int | None, Field(primary_key=True)] = None
    name: str
    email: Annotated[str, Field(unique=True)]

    posts: Relation[list["Post"]] = Reverse("author_id")


class Post(Model):
    id: Annotated[int | None, Field(primary_key=True)] = None
    title: str
    body: str
    published: bool = False
    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    author_id: Annotated[int, Field(foreign_key=Author)]

    author: Relation[Author] = Forward("author_id")

A Ferro model is a Pydantic model: annotated fields become columns, and defaults work as they do in Pydantic.

  • Field(default=None, primary_key=True) marks id as the primary key. The type is int | None because the database assigns the value on insert.
  • Field(unique=True) adds a unique constraint, and default_factory gives each post a creation timestamp in UTC.
  • author_id with Field(foreign_key=Author) is a foreign-key column: each Post stores the id of its Author. author: Relation[Author] = Forward("author_id") reads that author through it.
  • posts: Relation[list["Post"]] = Reverse("author_id") declares the reverse side, so author.posts becomes a query for the posts whose author_id is that author's.

Connect

Connect to a database, then open a session. Every ORM call runs inside async with engines.session():, and raises No database route outside it:

await connect("sqlite::memory:", auto_migrate=True)

async with engines.session():
    assert await Author.select().count() == 0

The new database has no authors yet, so the count is 0. connect() takes a database URL: sqlite::memory: is a throwaway in-memory database, sqlite:app.db?mode=rwc is a file that is created if missing (rwc means read, write, create), and a postgres://... URL connects to PostgreSQL. auto_migrate=True creates a table for every registered model on connect. Use it in development and tests; for a database whose data you would mind losing, use migrations (ferro migrate new, then ferro migrate up), which Schema management compares with auto-migrate.

The blocks that follow run inside this session. See Sessions for named connections and request-scoped sessions.

Create data

Create an author and a first post, then insert two more posts in one statement with bulk_create():

alice = await Author.create(name="Alice", email="alice@example.com")
post = await Post.create(
    title="Why Ferro is fast",
    body="Ferro hands SQL generation and row hydration to a Rust engine.",
    published=True,
    author_id=alice.id,
)
assert post.id == 1  # the database assigned it

await Post.bulk_create(
    [
        Post(
            title="Async patterns",
            body="One event loop, many queries.",
            published=True,
            author_id=alice.id,
        ),
        Post(
            title="Unfinished draft",
            body="Still to write.",
            author_id=alice.id,
        ),
    ]
)
assert await Post.select().count() == 3

create() validates the data, inserts one row and returns the instance with its database-assigned id. Passing author_id=alice.id sets the foreign key. A duplicate unique value raises UniqueViolationError; create() never overwrites a row. bulk_create() writes the whole batch at once, so use it whenever you load more than a handful of rows. The table now holds three posts.

Query

Fetch the first post by primary key:

same_post = await Post.get(post.id)
assert same_post is post  # one row, one object

get() returned the same Python object as the post you created, because within a session one database row is one object. See Identity map.

Filter, order and slice the posts:

published = (
    await Post.where(lambda post: post.published == True)
    .order_by(lambda post: post.title)
    .limit(10)
    .all()
)
assert [post.title for post in published] == [
    "Async patterns",
    "Why Ferro is fast",
]

where() takes a lambda predicate, the only predicate style it accepts; name the parameter after the model in lowercase singular. order_by() and limit() shape the result, and nothing touches the database until a terminal such as .all(), .first(), .count() or .exists() runs. See Queries for the operators and how column names are checked when you build the query.

Count the posts and check for drafts:

total = await Post.select().count()
has_drafts = await Post.where(lambda post: post.published == False).exists()
assert (total, has_drafts) == (3, True)

There are three posts, and at least one is unpublished.

Relationships

Load a post's author, then the author's published posts:

author = await post.author.load()
assert author.name == "Alice"

alice_posts = await author.posts.where(
    lambda post: post.published == True
).all()
assert len(alice_posts) == 2

post.author is a forward relation: it reads as the Author its author_id points at. That is the complete instance an include() or .load() filled, or the session's instance for that key (here alice, created in this session), or else an unloaded Author holding only the key, which .load() fills in place and returns. The reverse side (author.posts) is a query, so you can chain .where() and .order_by() before awaiting it.

Update and delete

Change one post with save(), publish every draft with update() and remove a post with delete():

post.title = "Why Ferro is really fast"
await post.save()
assert (await Post.get(post.id)).title == "Why Ferro is really fast"

updated = await Post.where(lambda post: post.published == False).update(
    published=True
)
assert updated == 1

deleted = await Post.where(
    lambda post: post.title == "Unfinished draft"
).delete()
assert deleted == 1

save() updates an instance that came from the database and inserts one that did not; see Mutations. Chained .update(field=value) and .delete() act on every matching row and return the number of rows they changed, here 1 each.

Transactions

Create an author and their post together:

async with transaction():
    bob = await Author.create(name="Bob", email="bob@example.com")
    await Post.create(title="Hello", body="First post.", author_id=bob.id)
assert await Author.select().count() == 2  # both writes committed

Everything inside async with transaction(): commits when the block exits cleanly and rolls back if it raises. Use it whenever several writes must succeed or fail together. See Transactions.

Complete script

The whole tutorial as one runnable file, also at docs/examples/quickstart.py in the repository:

"""Runnable companion to the Quickstart tutorial (docs/pages/getting-started/quickstart.md)."""

import asyncio

from ferro import connect, engines, transaction


from datetime import UTC, datetime

from ferro import Field, Forward, Model, Relation, Reverse


class Author(Model):
    id: int | None = Field(default=None, primary_key=True)
    name: str
    email: str = Field(unique=True)

    posts: Relation[list["Post"]] = Reverse("author_id")


class Post(Model):
    id: int | None = Field(default=None, primary_key=True)
    title: str
    body: str
    published: bool = False
    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    author_id: int = Field(foreign_key=Author)

    author: Relation[Author] = Forward("author_id")




async def main() -> None:
    await connect("sqlite::memory:", auto_migrate=True)

    async with engines.session():
        assert await Author.select().count() == 0

        alice = await Author.create(name="Alice", email="alice@example.com")
        post = await Post.create(
            title="Why Ferro is fast",
            body="Ferro hands SQL generation and row hydration to a Rust engine.",
            published=True,
            author_id=alice.id,
        )
        assert post.id == 1  # the database assigned it

        await Post.bulk_create(
            [
                Post(
                    title="Async patterns",
                    body="One event loop, many queries.",
                    published=True,
                    author_id=alice.id,
                ),
                Post(
                    title="Unfinished draft",
                    body="Still to write.",
                    author_id=alice.id,
                ),
            ]
        )
        assert await Post.select().count() == 3

        same_post = await Post.get(post.id)
        assert same_post is post  # one row, one object

        published = (
            await Post.where(lambda post: post.published == True)
            .order_by(lambda post: post.title)
            .limit(10)
            .all()
        )
        assert [post.title for post in published] == [
            "Async patterns",
            "Why Ferro is fast",
        ]

        total = await Post.select().count()
        has_drafts = await Post.where(lambda post: post.published == False).exists()
        assert (total, has_drafts) == (3, True)

        author = await post.author.load()
        assert author.name == "Alice"

        alice_posts = await author.posts.where(
            lambda post: post.published == True
        ).all()
        assert len(alice_posts) == 2

        post.title = "Why Ferro is really fast"
        await post.save()
        assert (await Post.get(post.id)).title == "Why Ferro is really fast"

        updated = await Post.where(lambda post: post.published == False).update(
            published=True
        )
        assert updated == 1

        deleted = await Post.where(
            lambda post: post.title == "Unfinished draft"
        ).delete()
        assert deleted == 1

        async with transaction():
            bob = await Author.create(name="Bob", email="bob@example.com")
            await Post.create(title="Hello", body="First post.", author_id=bob.id)
        assert await Author.select().count() == 2  # both writes committed

    print("quickstart example ran successfully")


if __name__ == "__main__":
    asyncio.run(main())

Running it prints quickstart example ran successfully.

Next steps

Pick a path by what you are building.

For an API with FastAPI, Starlette or similar:

  1. Models and fields covers field types, constraints and defaults.
  2. Relationships covers foreign-key columns, forward and reverse relations and many-to-many.
  3. Queries covers filtering, ordering and slicing.
  4. Pagination shows offset and cursor pagination.
  5. Testing shows fast, isolated tests on in-memory SQLite.

For data processing and bulk loads:

  1. Mutations covers bulk_create and bulk update and delete.
  2. Transactions makes multi-step writes atomic.
  3. Queries shows how to filter in the database instead of in Python.

For shipping to production:

  1. Connections covers connection URLs and pool settings.
  2. Schema management and Deploying migrations cover evolving a production schema.
  3. CLI reference and Configuration list the ferro commands and settings.
  4. Multiple databases covers more than one database.

More recipes are under How-to guides, every public class and method is in the API reference, and Releases on GitHub lists new versions.