Platform 01–02 · Study guide
Build safe, fluent database queries and load relationships without N+1 loops.
Generate repositories with tpy build / tpy crud so each repo exposes query(). No extra install beyond your database driver.
from app.repositories.user_repository import UserRepository
repo = UserRepository()
rows = repo.query().where("email", "asha@example.com").get()
one = repo.query().find(user_id)
repo.query() returns a fluent builder bound to the model table.where), sorts (order_by), limits, etc.get, first, find, paginate) execute parameterized SQL (or Mongo helpers).page = (
repo.query()
.where("published", True)
.order_by("created_at", "desc")
.paginate(page=1, per_page=20)
)
model Post {
id: uuid primary
user_id: uuid references User on_delete cascade
title: string required
relations {
belongs_to User as author via user_id
}
}
model User {
id: uuid primary
email: string unique required
relations {
has_many Post as posts
}
}
| Kind | Meaning |
|---|---|
belongs_to | This row stores the foreign key |
has_many / has_one | Related rows point back |
belongs_to_many | Many-to-many through a pivot model |
posts = repo.query().with_("author").get()
# Avoids N+1: loads authors in a follow-up query, then attaches them
with_().