ORIONIS API REFERENCE

THE ORIONIS API

Build with clarity.

Explore the building blocks of an async-first Python framework. Every module, class, and method — connected, searchable, and ready to build with.

class documentation

Many-to-many relationship backed by an intermediate pivot table.

Mirrors Eloquent's BelongsToMany, with one deliberate difference: instead of compiling a single JOIN against the pivot table (which would require the SQL compiler to alias projected columns to avoid name collisions between both tables -- a feature it does not have yet), this relationship resolves in two steps:

  1. Query the pivot table for the related keys linked to the parent key(s) involved (orionis.orm.query.raw_builder.RawQueryBuilder, since the pivot table has no model).
  2. Query the related model table with whereIn(related_key, ids), reusing the regular, fully hydrated orionis.orm.query.ModelQueryBuilder machinery.

Composite pivot keys are out of scope: like the rest of the ORM, every key involved is a single column.

Static Method _defaultPivotTable Derive the conventional pivot table name for two model classes.
Method __init__ Bind the relationship.
Async Method _aggregate Constrain an aggregate query to the resolved pivot membership.
Async Method _currentRelatedIds Query the pivot table for the related ids currently linked.
Method _extractId Extract the related key value from a scalar or model instance.
Method _invalidatePivot Discard the resolved pivot rows and generated membership clause.
Method _normalizeIds Normalize a scalar, model, or iterable of either into id values.
Method _pivotQuery Build a model-less query targeting the pivot table.
Async Method _prepare Resolve the pivot rows once and constrain the query to their ids.
Async Method _resolvePivotMap Query the pivot table for the rows linking the captured parents.
Method addConstraints Capture the parent key used to resolve the pivot rows.
Method addEagerConstraints Capture every parent key involved in an eager-loaded batch.
Async Method attach Link the parent to the given related records via the pivot table.
Method clone Copy query clauses and pivot filters into an independent builder.
Async Method delete Delete related records linked through the pivot table.
Async Method detach Unlink the parent from the given related records.
Async Method exists Report whether at least one related row is linked.
Async Method first Execute the query and hydrate only the first linked related row.
Async Method forceDelete Permanently delete records linked through the pivot table.
Async Method get Execute the query and hydrate every linked related row.
Async Method getResults Retrieve every related row linked to the parent instance.
Method match Attach the matching related rows to each parent instance.
Async Method sync Attach exactly the given records, detaching every other one.
Async Method toggle Attach ids not currently linked, detach ids that already are.
Async Method update Update related records linked through the pivot table.
Method wherePivot Filter the pivot rows considered by this relationship query.
Class Variable __slots__ Declare the instance attribute slots reserved by this class.
Instance Variable _eager_keys_empty Whether eager loading has no parent keys to query.
Instance Variable _foreign_pivot_key Pivot column referencing the parent; defaults to snake_case(ParentClass) + "_id".
Instance Variable _parent_key Column on the parent matched against foreign_pivot_key; defaults to the parent's primary key.
Instance Variable _parent_keys Parent identifiers participating in the relation query.
Instance Variable _pivot_constraint Constraint used to scope the pivot-table query.
Instance Variable _pivot_wheres Predicates applied to the relation pivot table.
Instance Variable _prepare_lock Lock coordinating one-time preparation of the relation query.
Instance Variable _prepared Prepared flag used by BelongsToManyRelation.
Instance Variable _related_key Column on the related table matched against related_pivot_key; defaults to the related model's primary key.
Instance Variable _related_map Related models indexed for assignment to their parent objects.
Instance Variable _related_pivot_key Pivot column referencing the related row; defaults to snake_case(RelatedClass) + "_id".
Instance Variable _table Pivot table name; defaults to both model names in snake_case, singular, joined by "_" in alphabetical order (for instance role_user).

Inherited from Relation:

Class Method noConstraints Build a relationship instance without its single-parent constraint.
Method __await__ Allow await directly on a relationship without a terminal.
Async Method getEager Execute the relationship query assembled for eager loading.
Instance Variable _connection_name Use the parent's configured connection for an unbound related model.
Instance Variable _parent Model instance the relationship is accessed from.
Instance Variable _resolved_connection Retain the connection that owns the parent model's loaded state.

Inherited from IModelQueryBuilder (via Relation, IBelongsToManyRelation, IRelation):

Async Method find Retrieve a model by its primary key.
Async Method findOrFail Retrieve a model by primary key or raise when absent.
Async Method firstOrFail Return the first matching row or raise when none exists.
Method load Eager load the given relationships; alias of withRelations.
Async Method paginate Execute the query returning a length-aware page of results.
Async Method pluck Return one column of every matching row.
Async Method value Return a single column value of the first matching row.
Method withRelations Eager load the given relationships alongside the query.

Inherited from IQueryBuilderBase (via Relation, IBelongsToManyRelation, IRelation, IModelQueryBuilder):

Method addSelect Append columns to the current projection.
Async Method avg Return the average value of a column among matching rows.
Method chunks Iterate bounded, explicitly ordered result batches when supported.
Async Method count Count the rows matched by the query.
Method crossJoin Add a CROSS JOIN to the query.
Method distinct Collapse duplicate rows from the query results.
Async Method doesntExist Report whether the query matches no rows.
Method forPage Limit the query to a single page of results.
Method fullJoin Add a FULL OUTER JOIN to the query.
Method groupBy Add grouping columns to the query.
Method having Add a post-grouping condition to the query.
Method havingRaw Add a raw SQL post-grouping condition.
Async Method insert Insert one or many rows into the target table.
Method join Add an INNER JOIN to the query.
Method joinSub Join a subquery as a derived table with an INNER JOIN.
Method latest Order the query by a timestamp column in descending order.
Method leftJoin Add a LEFT OUTER JOIN to the query.
Method leftJoinSub Join a subquery as a derived table with a LEFT OUTER JOIN.
Method limit Limit the number of rows returned by the query.
Method lockForUpdate Lock the selected rows against concurrent writes.
Async Method max Return the maximum value of a column among matching rows.
Async Method min Return the minimum value of a column among matching rows.
Method offset Skip the given number of rows before returning results.
Method oldest Order the query by a timestamp column in ascending order.
Method orderBy Add an ordering rule to the query.
Method orHaving Add an OR-combined post-grouping condition to the query.
Method orWhere Add an OR-combined filtering condition.
Method orWhereColumn Add an OR-combined comparison between two columns.
Method orWhereExists Add an OR-combined EXISTS condition.
Method orWhereIn Add an OR-combined set-membership condition.
Method orWhereNotExists Add an OR-combined NOT EXISTS condition.
Method orWhereNotIn Add an OR-combined set-exclusion condition.
Method orWhereNotNull Add an OR-combined IS NOT NULL condition.
Method orWhereNull Add an OR-combined IS NULL condition.
Method orWhereRaw Add an OR-combined raw SQL condition.
Method rightJoin Add a RIGHT OUTER JOIN to the query.
Method rightJoinSub Join a subquery as a derived table with a RIGHT OUTER JOIN.
Method select Restrict the query projection to the given columns.
Method selectRaw Append a raw SQL fragment to the projection.
Method selectSub Append a scalar subquery to the projection under an alias.
Method sharedLock Lock the selected rows in shared mode.
Method skip Skip the given number of rows; alias of offset.
Async Method sum Return the sum of a column among matching rows.
Method take Limit the number of rows returned; alias of limit.
Method toPlan Return the engine-agnostic plan assembled so far.
Method toSql Render the current SELECT query without executing or mutating it.
Method union Append another query's rows, collapsing duplicates.
Method unionAll Append another query's rows, keeping duplicates.
Method where Add an AND-combined filtering condition.
Method whereBetween Filter rows whose column value lies between two boundaries.
Method whereColumn Compare two columns of the query against each other.
Method whereContains Filter rows whose column value contains the given text.
Method whereEndsWith Filter rows whose column value ends with the given text.
Method whereExists Keep rows for which a correlated subquery returns any row.
Method whereILike Filter rows matching a case-insensitive SQL LIKE pattern.
Method whereIn Filter rows whose column value belongs to the given set.
Method whereLike Filter rows whose column value matches an SQL LIKE pattern.
Method whereNotBetween Filter rows whose column value lies outside two boundaries.
Method whereNotExists Keep rows for which a correlated subquery returns no row.
Method whereNotILike Filter rows not matching a case-insensitive LIKE pattern.
Method whereNotIn Filter rows whose column value is outside the given set.
Method whereNotLike Filter rows not matching an SQL LIKE pattern.
Method whereNotNull Filter rows whose column value is not NULL.
Method whereNull Filter rows whose column value is NULL.
Method whereRaw Add an AND-combined raw SQL condition.
Method whereRegexpMatch Filter rows whose column value matches a regular expression.
Method whereStartsWith Filter rows whose column value starts with the given text.
def _defaultPivotTable(parent_cls: type[_orm.Model], related: type[_orm.Model]) -> str: (source)

Derive the conventional pivot table name for two model classes.

Parameters
parent_cls:type of orionis.orm.ModelParent model class.
related:type of orionis.orm.ModelRelated model class.
Returns
strBoth class names in snake_case, alphabetically joined by "_".
def __init__(self, parent: _orm.Model, related: type[TRelated], table: str | None, foreign_pivot_key: str | None, related_pivot_key: str | None, parent_key: str | None, related_key: str | None): (source)

Bind the relationship.

Parameters
parent:orionis.orm.ModelModel instance the relationship is accessed from.
related:type of orionis.orm.ModelModel class the relationship targets.
table:str or NonePivot table name; defaults to both model names in snake_case, singular, joined by "_" in alphabetical order (for instance role_user).
foreign_pivot_key:str or NonePivot column referencing the parent; defaults to snake_case(ParentClass) + "_id".
related_pivot_key:str or NonePivot column referencing the related row; defaults to snake_case(RelatedClass) + "_id".
parent_key:str or NoneColumn on the parent matched against foreign_pivot_key; defaults to the parent's primary key.
related_key:str or NoneColumn on the related table matched against related_pivot_key; defaults to the related model's primary key.
Returns
NoneNo return value.
async def _aggregate(self, function: AggregateFunction, column: str) -> Any: (source)

Constrain an aggregate query to the resolved pivot membership.

Parameters
function:orionis.orm.query.AggregateFunctionAggregate operation to perform.
column:strRelated-model column passed to the aggregate operation.
Returns
typing.AnyResult returned by the query builder's aggregate operation.
async def _currentRelatedIds(self) -> list[Any]: (source)

Query the pivot table for the related ids currently linked.

Returns
listRelated ids currently linked to the parent instance.
def _extractId(self, item: Any) -> Any: (source)

Extract the related key value from a scalar or model instance.

Parameters
item:typing.AnyRelated id, or a model instance to read the related key from.
Returns
typing.AnyRelated id value.
def _invalidatePivot(self): (source)

Discard the resolved pivot rows and generated membership clause.

Returns
NoneNo return value.
def _normalizeIds(self, ids: Any) -> list[Any]: (source)

Normalize a scalar, model, or iterable of either into id values.

Parameters
ids:typing.AnyA related id, model instance, or iterable of either.
Returns
listRelated id values.
def _pivotQuery(self) -> RawQueryBuilder: (source)

Build a model-less query targeting the pivot table.

Returns
orionis.orm.query.raw_builder.RawQueryBuilderFresh builder bound to the pivot table and the connection the relationship runs on.
async def _prepare(self) -> bool: (source)

Resolve the pivot rows once and constrain the query to their ids.

Idempotent: repeated terminal calls on the same relationship instance reuse the first resolution instead of re-querying the pivot table.

Returns
boolTrue when at least one related id was found.
async def _resolvePivotMap(self) -> dict[Any, list[Any]]: (source)

Query the pivot table for the rows linking the captured parents.

Returns
dictRelated ids grouped by the parent key that links to them.
def addConstraints(self): (source)

Capture the parent key used to resolve the pivot rows.

The pivot query itself is deferred to orionis.orm.relations.BelongsToManyRelation.get/other terminals, since resolving it requires an awaited query the constructor cannot perform.

Returns
NoneNo return value.
def addEagerConstraints(self, models: list[_orm.Model]): (source)

Capture every parent key involved in an eager-loaded batch.

Parameters
models:list of orionis.orm.ModelParent instances being eager loaded together.
Returns
NoneNo return value.
async def attach(self, ids: Any, attributes: dict[str, Any] | None = None) -> int: (source)

Link the parent to the given related records via the pivot table.

Parameters
ids:typing.AnyA related id, model instance, iterable of either, or a mapping of id (or model) to per-row pivot attributes.
attributes:dict or None, optionalExtra pivot column values applied to every inserted row when ids is not already a mapping.
Returns
intNumber of pivot rows inserted.
def clone(self) -> Self: (source)

Copy query clauses and pivot filters into an independent builder.

Returns
typing.SelfIndependent relationship builder with copied query state.
async def delete(self) -> int: (source)

Delete related records linked through the pivot table.

Returns
intNumber of linked related records deleted.
async def detach(self, ids: Any = None) -> int: (source)

Unlink the parent from the given related records.

Parameters
ids:typing.Any, optionalA related id, model instance, or iterable of either; None detaches every related record currently linked.
Returns
intNumber of pivot rows deleted.
async def exists(self) -> bool: (source)

Report whether at least one related row is linked.

Returns
boolTrue when a linked related row exists.
async def first(self) -> TRelated | None: (source)

Execute the query and hydrate only the first linked related row.

Returns
orionis.orm.Model or NoneFirst linked related model, or None without matches.
async def forceDelete(self) -> int: (source)

Permanently delete records linked through the pivot table.

Returns
intNumber of linked related records permanently deleted.
async def get(self) -> Collection: (source)

Execute the query and hydrate every linked related row.

Returns
orionis.support.types.CollectionCollection of hydrated related model instances.
async def getResults(self) -> Collection: (source)

Retrieve every related row linked to the parent instance.

Returns
orionis.support.types.CollectionRelated models; empty when the parent has no key or no pivot row links it to anything.
def match(self, models: list[_orm.Model], results: Collection, name: str): (source)

Attach the matching related rows to each parent instance.

Parameters
models:list of orionis.orm.ModelParent instances being eager loaded together.
results:orionis.support.types.CollectionRelated rows produced by getEager.
name:strRelationship name the results are stored under.
Returns
NoneNo return value.
async def sync(self, ids: Iterable[Any]) -> dict[str, list[Any]]: (source)

Attach exactly the given records, detaching every other one.

Parameters
ids:collections.abc.IterableRelated ids or model instances that must remain attached.
Returns
dict of str to list"attached" and "detached" related id lists.
async def toggle(self, ids: Iterable[Any]) -> dict[str, list[Any]]: (source)

Attach ids not currently linked, detach ids that already are.

Parameters
ids:collections.abc.IterableRelated ids or model instances to toggle.
Returns
dict of str to list"attached" and "detached" related id lists.
async def update(self, values: dict[str, Any]) -> int: (source)

Update related records linked through the pivot table.

Parameters
values:dict of str to typing.AnyColumn values to apply to the linked related records.
Returns
intNumber of related records updated.
def wherePivot(self, column: str, *args: Any) -> BelongsToManyRelation[TRelated]: (source)

Filter the pivot rows considered by this relationship query.

Parameters
column:strPivot table column name.
*args:typing.AnyEither the bound value, or an operator followed by a value.
Returns
orionis.orm.relations.BelongsToManyRelationThe same relationship, enabling fluent chaining.
__slots__: tuple[str, ...] = (source)

Declare the instance attribute slots reserved by this class.

_eager_keys_empty = (source)

Whether eager loading has no parent keys to query.

_foreign_pivot_key = (source)

Pivot column referencing the parent; defaults to snake_case(ParentClass) + "_id".

_parent_key = (source)

Column on the parent matched against foreign_pivot_key; defaults to the parent's primary key.

_parent_keys: tuple[Any, ...] = (source)

Parent identifiers participating in the relation query.

_pivot_constraint: WhereClause | None = (source)

Constraint used to scope the pivot-table query.

_pivot_wheres: list[tuple[str, tuple[Any, ...]]] = (source)

Predicates applied to the relation pivot table.

_prepare_lock: asyncio.Lock | None = (source)

Lock coordinating one-time preparation of the relation query.

_prepared: bool = (source)

Prepared flag used by BelongsToManyRelation.

_related_key = (source)

Column on the related table matched against related_pivot_key; defaults to the related model's primary key.

_related_map: dict[Any, list[Any]] = (source)

Related models indexed for assignment to their parent objects.

_related_pivot_key = (source)

Pivot column referencing the related row; defaults to snake_case(RelatedClass) + "_id".

Pivot table name; defaults to both model names in snake_case, singular, joined by "_" in alphabetical order (for instance role_user).