5.5 · Reference
Models and queries¶
Concrete models may omit @db.table(...) (or the compatible table= class
keyword) to derive the table name <app>_<models> from the model's package and class name;
label= and plural= override humanized display names. Explicit table names
remain the safe choice for migration-backed histories and stable physical names.
hinoki.orm.Model ¶
Base class: class Post(Model): ... with an optional table= override.
__column_readers__
class-attribute
¶
__column_readers__: dict[
str, tuple[str, Callable[[Any], Any]]
] = {}
__field_validators__
class-attribute
¶
__field_validators__: dict[
str, tuple[Callable[..., None], ...]
] = {}
__field_validation_fields__
class-attribute
¶
__field_validation_fields__: frozenset[str] = frozenset()
is_dirty
property
¶
is_dirty: bool
True for a new instance and for one whose columns differ from
the stored values.
changes
property
¶
changes: dict[str, Change]
The columns that differ from the stored row, as Change(old, new).
A new instance reports every column with old=UNSET. Computed when
read: nothing is tracked on assignment.
__init_subclass__ ¶
__init_subclass__(
table: str = "",
unique: Sequence[Sequence[str]] = (),
label: str = "",
plural: str = "",
abstract: bool = False,
app: str = "",
**kwargs: object,
) -> None
check_field_conflicts
classmethod
¶
check_field_conflicts() -> None
Two bases may not give one field name different types: which one the model would get depends on base order, and the other would be lost. A base that overrides its own parent, or the class redeclaring the field, is a decision and is accepted.
check_field_validations
classmethod
¶
check_field_validations(
columns: tuple[Field[Any], ...],
annotations: dict[str, object],
) -> dict[str, FieldType]
Validate constraints against annotations and reject async callbacks.
validate_values
classmethod
¶
validate_values(values: dict[str, Any]) -> None
Run declared field checks on values about to be written.
adopt_mixin_fields
classmethod
¶
adopt_mixin_fields() -> None
Field annotations of plain (non-model, non-dataclass) bases become
fields of this class. dataclasses reads only a class's own
annotations and its dataclass bases, so without this a mixin's fields
would be dropped without a word.
_adopt_mixin_base
classmethod
¶
_adopt_mixin_base(
base: type,
decided: set[str],
adopted: dict[str, object],
) -> None
option_bases
classmethod
¶
option_bases() -> list[type[Model]]
The abstract models this class is declared on. Each already holds what it inherited and what it replaced, so nothing further up is read again; a concrete parent keeps its options to itself.
inherit_options
classmethod
¶
inherit_options(unique: Sequence[Sequence[str]]) -> None
Options come from the abstract bases the class lists: every such
base's constraints and indexes, and the first one that sets an order or
a timestamp column. A decorator applied to this class later replaces what
was inherited for its kind (see hinoki.orm.options). Indexes declared
with field(index=True) belong to their column: they stay while the
column keeps index=True and go when this class redeclares the column
without it, whether or not a decorator is applied.
keeps_index
classmethod
¶
keeps_index(
base: type[Model], columns: tuple[str, ...]
) -> bool
Whether an index of base carries over: a decorator index always
does, a field(index=True) index only while this class's column still
declares it.
check_table
classmethod
¶
check_table() -> None
Raise the deferred error of a derived table name that cannot be
used: the class name gave no portable or free name and no
@db.table/table= replaced it.
replace_inherited
classmethod
¶
replace_inherited(kind: str) -> bool
True the first time an option of kind is applied to a class that
inherited that kind: the caller then starts from nothing.
concrete
classmethod
¶
concrete() -> type[Self]
This class, refusing an abstract model: it has no table to query.
check_unique
classmethod
¶
check_unique(
groups: Sequence[Sequence[str]],
) -> tuple[tuple[str, ...], ...]
Composite uniqueness, e.g. unique=[("post_id", "tag_id")] on a
many-to-many join model. Single columns use field(unique=True).
check_names
classmethod
¶
check_names(columns: tuple[str, ...]) -> None
A column named like a Model method would hide it on every instance.
check_set_null
classmethod
¶
check_set_null(column: Field[Any], meta: FieldMeta) -> None
set_null on a column that cannot hold NULL fails every delete of
the referenced row, so it is refused when the model is declared. An
annotation that cannot be resolved yet is left to the migration plan.
register_relations
classmethod
¶
register_relations(fields: tuple[Field[Any], ...]) -> None
Foreign keys this class declares or takes from an abstract base or a mixin (those of a concrete parent come with it). Every check runs before anything is attached, so a failing definition leaves the referenced models untouched.
reverse_name
classmethod
¶
reverse_name(column: str, related_name: str) -> str
related_name with {model} replaced by this class's name in
lower case, so one declaration in an abstract base or a mixin gives
each concrete model its own reverse relation.
row_plan
classmethod
¶
row_plan() -> core._ModelRows | None
The native row builder for this model, or None when its
instances must go through from_row (a custom constructor or
allocator, columns that need a reader, or an overridden or patched
from_row, remember or __post_init__). The builder is made
once per class; the cheap override checks run on every call.
_stored_values
classmethod
¶
_stored_values(row: dict[str, Any]) -> dict[str, Any]
Objects for the columns that store a plain form: addresses, dates, times, durations, decimals and enum members.
was_changed ¶
was_changed(name: str) -> bool
Whether column name differs from the stored row (always True
for a new instance).
after_commit ¶
after_commit(callback: Callable[[], object]) -> None
Run callback (sync or async) once the surrounding transaction
commits; never after a rollback. Meant for after_* hooks.
before_save ¶
before_save() -> Awaitable[None] | None
Hook: runs before every write of this instance; values may still change.
before_create ¶
before_create() -> Awaitable[None] | None
Hook: runs before a new instance is first written, after before_save.
after_create ¶
after_create() -> Awaitable[None] | None
Hook: runs after the row is inserted, before after_save.
after_save ¶
after_save() -> Awaitable[None] | None
Hook: runs after the row is written, inside the transaction.
write_hooks
classmethod
¶
write_hooks() -> tuple[str, ...]
The hooks this model overrides, looked up on each write so a hook assigned after the class was created is not missed.
hook_transaction
staticmethod
¶
hook_transaction() -> AbstractAsyncContextManager[Any]
The transaction a hooked write runs in: a savepoint when one is open
(see write_transaction).
run_hooks
async
¶
run_hooks(*names: str) -> None
Run the overridden hooks among names, def or async def.
asave
async
¶
asave() -> Self
Insert a new instance, or update the columns changed since it was
loaded. Typed: Post(title="x", ...) is checked by the type checker.
save_with
async
¶
save_with(scope: QuerySet[Any] | None) -> Self
asave; with scope the UPDATE carries that query's conditions, so a
row that left the scope since it was read is refused (Model.NotFound)
instead of written.
aupdate_within
async
¶
aupdate_within(
scope: QuerySet[Any], /, **values: Any
) -> Self
assign then a save whose UPDATE carries scope's conditions (the
generated CRUD update uses it so ownership and visibility hold at write
time). A failed write leaves the instance as it was.
write_update
async
¶
write_update(scope: QuerySet[Any] | None = None) -> bool
Write the changed columns and load the stored row, without taking a
new snapshot; False when nothing changed.
insert
async
¶
insert(*, returning: bool = True) -> Self
Insert this instance and load the stored row into it. With
returning=False nothing is read back: the instance keeps the values
it sent (every column is sent, defaults and factories applied).
from_schema
classmethod
¶
from_schema(
data: Schema | None = None, /, **values: Any
) -> Self
An unsaved instance from a schema's values plus values. Explicit
keyword values win over the schema's, so a column the server assigns
(owner, state) can never come from the client.
acreate
async
classmethod
¶
acreate(
data: Schema | None = None,
/,
*,
returning: bool = True,
**values: Any,
) -> Self
Insert a row (defaults and factories apply) and return it:
await Post.acreate(data, author_id=me) or acreate(title="x").
returning=False: the instance holds the sent values, not re-read.
assign ¶
assign(
data: Schema | None = None, /, **values: Any
) -> Self
Set fields from a schema (fields the client left UNSET are
untouched) and keyword values, without touching the database.
aupdate_from
async
¶
aupdate_from(
data: Schema | None = None, /, **values: Any
) -> Self
assign then asave: only the columns that changed are written.
aget
async
classmethod
¶
aget(**conditions: Any) -> Self
Exactly one row, else Model.NotFound / MultipleObjectsReturned.
aupdate
async
classmethod
¶
aupdate(
*, returning: Literal[True] = ..., **values: Any
) -> Self
aupdate(*, returning: Literal[False], **values: Any) -> int
aupdate(*, returning: bool, **values: Any) -> Self | int
aupdate(
*, returning: bool = True, **values: Any
) -> Self | int
Update by primary key (id=...) and return the updated row.
returning=False reads nothing back and returns the row count the
database reports (no NotFound: 0 means no row was written).
aupdate_where
async
classmethod
¶
aupdate_where(
conditions: dict[str, Any],
values: dict[str, Any],
*,
returning: Literal[True] = ...,
) -> list[Self]
aupdate_where(
conditions: dict[str, Any],
values: dict[str, Any],
*,
returning: Literal[False],
) -> int
aupdate_where(
conditions: dict[str, Any],
values: dict[str, Any],
*,
returning: bool,
) -> list[Self] | int
aupdate_where(
conditions: dict[str, Any],
values: dict[str, Any],
*,
returning: bool = True,
) -> list[Self] | int
Update every row matching conditions and return the new rows
(or, with returning=False, the row count the database reports).
Conditions are part of the statement, so a row that stopped matching
(for example after a concurrent owner change) is not touched.
adelete
async
classmethod
¶
adelete(**conditions: Any) -> int
Delete matching rows; returns how many. An empty condition set is refused so a missing filter cannot wipe the table.
abulk_create
async
classmethod
¶
abulk_create(
items: Iterable[Schema | dict[str, Any]],
/,
*,
returning: bool = True,
) -> list[Self]
Insert many rows in one transaction: all of them or none. Each item is a
Schema or a dict of field values; defaults, factories, validation and
write hooks apply exactly as for acreate. Returns the rows in order.
abulk_update
async
classmethod
¶
abulk_update(instances: Iterable[Self]) -> list[Self]
Save the changes of many loaded instances in one transaction: all of them or none. Unchanged instances write nothing; an unsaved one is refused.
abulk_delete
async
classmethod
¶
abulk_delete(items: Iterable[Self | Any]) -> int
Delete many rows by instance or primary-key value in one transaction; returns how many existed. Nothing is deleted for an empty list.
delete_key
classmethod
¶
delete_key(item: Self | Any) -> Any
The primary-key value abulk_delete removes for item.
create
classmethod
¶
create(
data: Schema | None = None,
/,
*,
returning: bool = True,
**values: Any,
) -> Self
Sync acreate for sync handlers.
update_from ¶
update_from(
data: Schema | None = None, /, **values: Any
) -> Self
Sync aupdate_from for sync handlers.
update_where
classmethod
¶
update_where(
conditions: dict[str, Any],
values: dict[str, Any],
*,
returning: Literal[True] = ...,
) -> list[Self]
update_where(
conditions: dict[str, Any],
values: dict[str, Any],
*,
returning: Literal[False],
) -> int
update_where(
conditions: dict[str, Any],
values: dict[str, Any],
*,
returning: bool,
) -> list[Self] | int
update_where(
conditions: dict[str, Any],
values: dict[str, Any],
*,
returning: bool = True,
) -> list[Self] | int
Sync aupdate_where for sync handlers.
update
classmethod
¶
update(
*, returning: Literal[True] = ..., **values: Any
) -> Self
update(*, returning: Literal[False], **values: Any) -> int
update(*, returning: bool, **values: Any) -> Self | int
update(
*, returning: bool = True, **values: Any
) -> Self | int
Sync aupdate for sync handlers.
bulk_create
classmethod
¶
bulk_create(
items: Iterable[Schema | dict[str, Any]],
/,
*,
returning: bool = True,
) -> list[Self]
Sync abulk_create for sync handlers.
bulk_update
classmethod
¶
bulk_update(instances: Iterable[Self]) -> list[Self]
Sync abulk_update for sync handlers.
bulk_delete
classmethod
¶
bulk_delete(items: Iterable[Self | Any]) -> int
Sync abulk_delete for sync handlers.
merged_values
classmethod
¶
merged_values(
data: Schema | None, values: dict[str, Any]
) -> dict[str, Any]
The schema's values with explicit values winning, every name
checked. A schema may never carry the primary key: the client must not
choose a row's identity (pass it as a keyword when the server does).
hinoki.orm.field ¶
field(
*,
primary_key: bool = False,
unique: bool = False,
index: bool = False,
max_length: int | None = None,
constraints: FieldInfo | None = None,
validators: Sequence[Callable[..., None]] = (),
default: Any = dataclasses.MISSING,
default_factory: Callable[[], Any]
| Any = dataclasses.MISSING,
) -> Any
Declare a column and, optionally, write-time constraints and validators.
id: UUID = field(primary_key=True, default_factory=uuid4)
name: str = field(constraints=Field(min_length=1), validators=(check_name,))
created_at: datetime = field(index=True, default_factory=utc_now) adds a
single-column index, the same index as @db.indexed("created_at").
Constraints run before ORM writes. Custom validators are synchronous and
raise ValueError to refuse a value; they must not perform I/O.
hinoki.orm.pk ¶
pk(
*,
max_length: int | None = None,
constraints: FieldInfo | None = None,
validators: Sequence[Callable[..., None]] = (),
default: Any = dataclasses.MISSING,
default_factory: Callable[[], Any]
| Any = dataclasses.MISSING,
) -> Any
Declare the primary key: shorthand for field(primary_key=True, ...).
id: UUID = pk(default_factory=uuid4)
It takes the options of field that make sense for a key; unique
and index are implied by the primary key.
Model write validation raises ModelValidationError from hinoki.errors, with field paths, stable codes and messages in details. See Model field constraints and validators.
hinoki.orm.foreign_key ¶
foreign_key(
model: type[Model],
*,
on_delete: OnDelete,
related_name: str = "",
unique: bool = False,
validators: Sequence[Callable[..., None]] = (),
default: Any = dataclasses.MISSING,
) -> Any
Declare a column that references model's primary key.
author_id: UUID = foreign_key(User, on_delete=OnDelete.RESTRICT)
on_delete is required and is an OnDelete member (RESTRICT,
CASCADE, SET_NULL or NO_ACTION), so a deletion rule is always a
decision; text such as "cascade" is refused. SET_NULL needs a
column annotated | None. The relation is
named after the column without _id and is loaded only by
select_related / prefetch_related.
hinoki.orm.OnDelete ¶
Bases: Enum
What the database does with the rows that reference a deleted row.
RESTRICT
class-attribute
instance-attribute
¶
RESTRICT = 'restrict'
Refuse the delete while referencing rows exist.
SET_NULL
class-attribute
instance-attribute
¶
SET_NULL = 'set_null'
Set the column to NULL; the field must be annotated | None.
NO_ACTION
class-attribute
instance-attribute
¶
NO_ACTION = 'no_action'
Like RESTRICT, checked by the database at the end of the statement.
hinoki.orm.unique ¶
unique(*columns: str) -> Callable[[M], M]
A composite uniqueness constraint over two or more columns (single
columns use field(unique=True)).
hinoki.orm.indexed ¶
indexed(*columns: str) -> Callable[[M], M]
A (non-unique) index over one or more columns, created by the migration
planner. A single column can use field(index=True) instead; naming a
column both ways creates one index.
hinoki.orm.table ¶
table(name: str) -> Callable[[M], M]
Name the model's table; without it the name is derived from the class
name. @table("saved_links") is the same as table="saved_links" in
the class header; giving both with different names is an error.
hinoki.orm.ordered_by ¶
ordered_by(*names: str) -> Callable[[M], M]
The default order of every query that does not call order_by;
"-created_at" is descending.
hinoki.orm.timestamps ¶
timestamps(
updated_at: str = "updated_at",
*,
clock: Clock = utc_now,
) -> Callable[[M], M]
Update a declared datetime column on each ORM update statement.
Timestamp columns remain ordinary model fields, visible to type checkers
and migrations. Declare their creation defaults with utc_now.
hinoki.orm.QuerySet ¶
Lazy, immutable query description; nothing runs until an a... call.
order
instance-attribute
¶
order = (
tuple(
(n.removeprefix("-"), n.startswith("-"))
for n in model.__ordering__
)
if order is None
else order
)
__init__ ¶
__init__(
model: type[M],
filters: tuple[tuple[str, str, list[Any]], ...] = (),
order: tuple[tuple[str, bool], ...] | None = None,
limit_to: int | None = None,
offset_by: int | None = None,
loading: Loading = Loading(),
) -> None
select_related ¶
select_related(*names: str) -> QuerySet[M]
Load forward relations in the same query (one JOIN each).
prefetch_related ¶
prefetch_related(*names: str) -> QuerySet[M]
Load relations (forward or reverse) with one extra query each.
joins ¶
joins(
counting: bool = False,
) -> list[tuple[str, str, str, str, bool, list[str]]]
Joins for selected relations (with columns) and filtered ones (without). A count needs only the filtered ones: loading a to-one relation cannot change the number of rows.
uses_stock_builders ¶
uses_stock_builders() -> bool
False when build or _hydrate was overridden or patched: the
native row builder would silently skip that code.
_hydrate
async
¶
_hydrate(rows: list[Row]) -> list[M]
Build and load rows already fetched by this query or a safe fallback.
aupdate
async
¶
aupdate(
values: dict[str, Any],
*,
returning: Literal[True] = ...,
) -> builtins.list[M]
aupdate(
values: dict[str, Any], *, returning: Literal[False]
) -> int
aupdate(
values: dict[str, Any], *, returning: bool
) -> builtins.list[M] | int
aupdate(
values: dict[str, Any], *, returning: bool = True
) -> builtins.list[M] | int
Update the rows this query matches (its filters are part of the
statement) and return them. Ordering and loading are ignored; a query
with limit or offset is refused, because the statement would
change every matching row. returning=False reads nothing back and
returns the row count the database reports instead.
adelete
async
¶
adelete() -> int
Delete the rows this query matches; returns how many. A query
without filters is refused so it cannot wipe the table, and so is one
with limit or offset: the statement would delete every match.
update ¶
update(
values: dict[str, Any],
*,
returning: Literal[True] = ...,
) -> builtins.list[M]
update(
values: dict[str, Any], *, returning: Literal[False]
) -> int
update(
values: dict[str, Any], *, returning: bool
) -> builtins.list[M] | int
update(
values: dict[str, Any], *, returning: bool = True
) -> builtins.list[M] | int
Sync aupdate.
stably_ordered ¶
stably_ordered() -> QuerySet[M]
The queryset with the primary key as the last sort key, so rows with equal sort values keep a fixed position from one page to the next.
apaginate
async
¶
apaginate(params: PageParams) -> Page[M]
One page plus the total. The primary key is the final sort key so pages are stable.
hinoki.pagination.PageParams
dataclass
¶
Validated request for one page (1-based).
hinoki.pagination.Page
dataclass
¶
One page of results plus the totals needed to navigate.
of
classmethod
¶
of(rows: Sequence[T], params: PageParams) -> Page[T]
Slice an in-memory sequence. Pages past the end are empty.
hinoki.pagination.PageNumberPagination
dataclass
¶
Strategy: ?page=N&page_size=M with a hard upper bound on the size.
A size left out (None) comes from the application's pagination
settings when the action is included, and from 20 / 100 without settings.
A size given here always wins.
sizes ¶
sizes() -> tuple[int, int]
(page_size, max_page_size) with the framework defaults filled in.
resolved ¶
resolved(
page_size: int = DEFAULT_PAGE_SIZE,
max_page_size: int = DEFAULT_MAX_PAGE_SIZE,
) -> PageNumberPagination
This strategy with every size left out filled from the defaults given;
sizes set on it are kept. Raises ValueError when the result is invalid.
parse ¶
parse(query: dict[str, list[str]]) -> PageParams
Read and validate the query; every problem is reported at once.
hinoki.orm.Related ¶
Class attribute that serves a loaded relation from the instance.
The framework installs it for every relation. To have the type checker know the attribute, declare it on the model without a value::
writer: ClassVar[Related[Writer]]
articles: ClassVar[Related[list[Article]]]
stale ¶
stale(instance: Any, value: Any) -> bool
The foreign key changed after the relation was loaded.