API Reference
This is the API reference for the ActiveRecordMixin
class.
Table of Contents
- API Reference
- Instance Methods
- Class Methods
- create
- insert
- add
- save_all
- create_all
- update_all
- delete_all
- destroy
- get
- get_or_fail
- options
- filter
- where
- find
- find_one
- find_one_or_none
- find_all
- find_first
- find_unique
- find_unique_all
- find_unique_first
- find_unique_one
- find_unique_one_or_none
- order_by
- sort
- offset
- skip
- limit
- take
- join
- with_subquery
- with_schema
- scalars
- first
- one
- one_or_none
- fetch_one
- fetch_one_or_none
- all
- fetch_all
- to_list
- unique
- unique_all
- unique_first
- unique_one
- unique_one_or_none
- smart_query
Instance Methods
fill
Fills the object with values from
kwargs
without saving to the database.Parameters:
kwargs
: Key-value pairs of attributes to set.Returns:
Self
: The instance itself for method chaining.Raises:
KeyError
: If attribute doesn't exist.Example:
save
Saves the current row to the database.
Returns:
Self
: The saved instance for method chaining.Raises: Any database errors are caught and will trigger a rollback.
Example:
update
Updates the current row with the provided values.
Parameters:
kwargs
: Key-value pairs of attributes to update.Returns:
Self
: The updated instance for method chaining.Raises: Any database errors are caught and will trigger a rollback.
Example:
edit
Synonym for
update()
.
delete
Deletes the current row from the database.
Raises: Any database errors are caught and will trigger a rollback.
Example:
remove
Synonym for
delete()
.
Class Methods
create
Creates a new row with the provided values.
Parameters:
kwargs
: Key-value pairs for the new instance.Returns:
Self
: The created instance for method chaining.Raises: Any database errors are caught and will trigger a rollback.
Example:
insert
Synonym for
create()
.
add
Synonym for
create()
.
save_all
Saves multiple rows in a single transaction.
Parameters:
rows
: Sequence of model instances to save.refresh
: Whether to refresh the instances after saving (default:False
).Raises: Any database errors are caught and will trigger a rollback.
Example:
create_all
Synonym for
save_all()
when creating new rows.
update_all
Synonym for
save_all()
when updating existing rows.
delete_all
Deletes multiple rows in a single transaction.
Parameters:
rows
: Sequence of model instances to delete.Raises: Any database errors are caught and will trigger a rollback.
Example:
destroy
Deletes multiple rows by their primary keys.
Parameters:
ids
: Primary key values of rows to delete.Raises: Any database errors are caught and will trigger a rollback.
Example:
get
async def get(
pk: object,
join: list[QueryableAttribute | tuple[QueryableAttribute, bool]] | None = None,
subquery: list[QueryableAttribute | tuple[QueryableAttribute, bool]] | None = None,
schema: dict[InstrumentedAttribute, str | tuple[str, dict[InstrumentedAttribute, Any]] | dict] | None = None,
)
Fetches a row by primary key.
Parameters:
pk
: Primary key value.join
: Paths to join eager load. See the docs ofjoin
method for details.subquery
: Paths to subquery eager load. See the docs ofwith_subquery
method for details.schema
: Schema for the eager loading. See the docs ofwith_schema
method for details.Returns:
Self | None
: Instance for method chaining orNone
if not found.Raises:
MultipleResultsFound
: If multiple rows match.Example:
get_or_fail
async def get_or_fail(
pk: object,
join: list[QueryableAttribute | tuple[QueryableAttribute, bool]] | None = None,
subquery: list[QueryableAttribute | tuple[QueryableAttribute, bool]] | None = None,
schema: dict[InstrumentedAttribute, str | tuple[str, dict[InstrumentedAttribute, Any]] | dict] | None = None,
)
Fetches a row by primary key or raises an exception if not found.
Parameters:
pk
: Primary key value.join
: Paths to join eager load. See the docs ofjoin
method for details.subquery
: Paths to subquery eager load. See the docs ofwith_subquery
method for details.schema
: Schema for the eager loading. See the docs ofwith_schema
method for details.Returns:
Self
: Instance for method chaining.Raises:
NoResultFound
: If no row is found.MultipleResultsFound
: If multiple rows match.Example:
options
Creates a query and applies the given list of mapper options.
Warning
Quoting from SQLAlchemy docs:
When including `joinedload()` in reference to a one-to-many or many-to-many collection, the `Result.unique()` method must be applied to the returned result, which will make the incoming rows unique by primary key that otherwise are multiplied out by the join. The ORM will raise an error if this is not present. This is not automatic in modern SQLAlchemy, as it changes the behavior of the result set to return fewer ORM objects than the statement would normally return in terms of number of rows. Therefore SQLAlchemy keeps the use of Result.unique() explicit, so there is no ambiguity that the returned objects are made unique on primary key.
To learn more about options, see
sqlalchemy.orm.Query.options
docs.Parameters:
args
: Mapper options.Returns:
AsyncQuery
: Async query instance for chaining.Example:
filter
Creates a filtered query using SQLAlchemy or Django-style filters.
Parameters:
criterion
: SQLAlchemy style filter expressions.filters
: Django-style filters.Returns:
AsyncQuery
: Async query instance for chaining.Example:
where
Synonym for
filter()
.
find
Synonym for
filter()
.
find_one
Finds a single row matching the criteria.
This is same as calling
await cls.find(*criterion, **filters).one()
.Returns:
Self
: Instance for method chaining.Raises:
NoResultFound
: If no row is found.MultipleResultsFound
: If multiple rows match.Example:
find_one_or_none
Finds a single row matching the criteria or
None
.This is same as calling
await cls.find(*criterion, **filters).one_or_none()
.Returns:
Self | None
: Instance for method chaining orNone
.Raises:
MultipleResultsFound
: If multiple rows match.Example:
find_all
Finds all rows matching the criteria.
This is same as calling
await cls.find(*criterion, **filters).all()
.Returns:
list[Self]
: List of instances for method chaining.Example:
find_first
Finds a single row matching the criteria or
None
.This is same as calling
await cls.find(*criterion, **filters).first()
.Returns:
Self | None
: Instance for method chaining orNone
.Example:
find_unique
Finds all unique rows matching the criteria and returns an
ScalarResult
object with them.This is same as calling
await cls.find(*criterion, **filters).unique()
.Returns:
sqlalchemy.engine.ScalarResult
: Scalars.Example:
find_unique_all
Finds all unique rows matching the criteria and returns a list.
This is same as calling
await cls.find(*criterion, **filters).unique_all()
.Returns:
list[Self]
: List of instances.Example:
find_unique_first
Finds a single unique row matching the criteria or
None
.This is same as calling
await cls.find(*criterion, **filters).unique_first()
.Returns:
Self | None
: Instance for method chaining orNone
.Example:
find_unique_one
Finds a single unique row matching the criteria.
This is same as calling
await cls.find(*criterion, **filters).unique_one()
.Returns:
Self
: Instance for method chaining.Raises:
NoResultFound
: If no row is found.MultipleResultsFound
: If multiple rows match.Example:
find_unique_one_or_none
Finds a single unique row matching the criteria or
None
.This is same as calling
await cls.find(*criterion, **filters).unique_one_or_none()
.Returns:
Self | None
: Instance for method chaining orNone
.Raises:
MultipleResultsFound
: If multiple rows match.Example:
order_by
Creates a query with ORDER BY clause.
Parameters:
columns
: Column names or SQLAlchemy column expressions.Returns:
AsyncQuery
: Async query instance for chaining.Example:
sort
Synonym for
order_by()
.
offset
Creates a query with OFFSET clause.
Parameters:
offset
: Number of rows to skip.Returns:
AsyncQuery
: Async query instance for chaining.Raises:
ValueError
: If offset is negative.Example:
skip
Synonym for
offset()
.
limit
Creates a query with LIMIT clause.
Parameters:
limit
: Maximum number of rows to return.Returns:
AsyncQuery
: Async query instance for chaining.Raises:
ValueError
: If limit is negative.Example:
take
Synonym for
limit()
.
join
Creates a query with
LEFT OUTER JOIN
eager loading.When a tuple is passed, the second element must be boolean. If it is
True
, the join isINNER JOIN
, otherwiseLEFT OUTER JOIN
.Parameters:
paths
: Relationship attributes to join.Returns:
AsyncQuery
: Async query instance for chaining.Example:
with_subquery
Creates a query with subquery or selectin loading.
Emits a second
SELECT
statement (Subqueryload) for each relationship to be loaded, across all result objects at once.When a tuple is passed, the second element must be boolean. If it is
True
, the eager loading strategy isSELECT IN
(Selectinload), otherwiseSELECT JOIN
(Subqueryload).Warning
A query which makes use of
subqueryload()
in conjunction with a limiting modifier such asQuery.limit()
orQuery.offset()
should always includeQuery.order_by()
against unique column(s) such as the primary key, so that the additional queries emitted bysubqueryload()
include the same ordering as used by the parent query. Without it, there is a chance that the inner query could return the wrong rows, as specified in SQLAlchemy docs.Parameters:
paths
: Relationship attributes to load.Returns:
AsyncQuery
: Async query instance for chaining.Example:
with_schema
def with_schema(
schema: dict[InstrumentedAttribute, str | tuple[str, dict[InstrumentedAttribute, Any]] | dict]
)
Creates a query with complex eager loading schema.
Useful for complex cases where you need to load nested relationships in separate queries.
Parameters:
schema
: Dictionary defining the loading strategy.Returns:
AsyncQuery
: Async query instance for chaining.
scalars
Returns a
sqlalchemy.engine.ScalarResult
object containing all rows.Returns:
sqlalchemy.engine.ScalarResult
: Scalars.Example:
first
Fetches the first row.
Returns:
Self | None
: Instance for method chaining orNone
if no matches.Example:
one
Fetches exactly one row.
Returns:
Self
: Instance for method chaining.Raises:
NoResultFound
: If no row is found.MultipleResultsFound
: If multiple rows match.Example:
one_or_none
Fetches exactly one row or
None
.Returns:
Self | None
: Instance for method chaining orNone
.Raises:
MultipleResultsFound
: If multiple rows match.Example:
fetch_one
Synonym for
one()
.
fetch_one_or_none
Synonym for
one_or_none()
.
all
Fetches all rows.
Returns:
list[Self]
: List of instances.Example:
fetch_all
Synonym for
all()
.
to_list
Synonym for
all()
.
unique
Returns a
sqlalchemy.engine.ScalarResult
object containing all unique rows.Returns:
sqlalchemy.engine.ScalarResult
: Scalars.Example:
unique_all
Fetches all unique rows.
Returns:
list[Self]
: List of instances.Example:
unique_first
Fetches the first unique row.
Returns:
Self | None
: Instance for method chaining orNone
.Example:
unique_one
Fetches exactly one unique row.
Returns:
Self
: Instance for method chaining.Raises:
NoResultFound
: If no row is found.MultipleResultsFound
: If multiple rows match.Example:
unique_one_or_none
Fetches exactly one unique row or
None
.Returns:
Self | None
: Instance for method chaining orNone
.Raises:
MultipleResultsFound
: If multiple rows match.Example:
smart_query
def smart_query(
criterion: Sequence[_ColumnExpressionArgument[bool]] | None = None,
filters: dict[str, Any] | dict[OperatorType, Any] | list[dict[str, Any]] | list[dict[OperatorType, Any]] | None = None,
sort_columns: Sequence[_ColumnExpressionOrStrLabelArgument[Any]] | None = None,
sort_attrs: Sequence[str] | None = None,
schema: dict[InstrumentedAttribute, str | tuple[str, dict[InstrumentedAttribute, Any]] | dict] | None = None,
)
Creates a query combining filtering, sorting, and eager loading.
Parameters:
criterion
: SQLAlchemy filter expressions.filters
: Django-style filters.sort_columns
: SQLAlchemy columns to sort by.sort_attrs
: String column names to sort by.schema
: Eager loading schema.Returns:
AsyncQuery
: Async query instance for chaining.Example: