Skip to content

Query

Model.where(...) and Model.select() return a Query: an immutable, chainable builder that runs when you await all(), first(), count(), exists(), update() or delete(). Predicates are lambdas over a QueryProxy, which checks every column name against the model when the query is built:

popular = await Post.where(lambda post: post.views > 1000).order_by("title").all()
assert [post.title for post in popular] == ["Notes on the Analytical Engine"]

The query ran once, at all(), and returned the one post with more than 1,000 views.

The Queries guide covers each feature with worked examples:

  • ~ negates any predicate, rendering SQL NOT (...): Negation and NULL values.
  • A lambda that follows a foreign key adds one INNER JOIN per relation path; left_join() keeps rows without the relation: Querying across relationships.
  • A reverse (Reverse) or many-to-many (ManyToMany) relation in a predicate takes one verb, .exists(), rendered as a correlated EXISTS: Existence tests.
  • include() returns each result with a forward relation loaded, so reading its columns runs no query; without it the relation is an unloaded instance that .load() fills: Loading relations with include().
  • nulls= on order_by() defaults to NULLS LAST on every backend: Ordering, limit and offset.

select() overloads

select() has four forms, resolved when the query is built:

Call Returns Result of .all()
Post.select() Query[Post] list[Post]: the full query, unchanged.
Post.select(lambda post: (post.id, post.author.name)) ProjectedQuery[Post] Rows[Row]: one record per row; a field may follow forward relations at any depth and takes the leaf column's name (one field: select(lambda post: post.views)).
Post.select(lambda post: {"author_email": post.author.email}) ProjectedQuery[Post] Rows[Row]: the dict keys name the output fields; the values are field references or aggregates.
Post.select("id", "views") ProjectedQuery[Post] Rows[Row]: root columns only, never a traversal, never mixed with a lambda.

A ProjectedQuery chains like a Query (where(), order_by(), limit(), offset(), first(), count(), exists()). update(), delete(), a second select(), two fields with one output name and a nested selector raise when the query is built. See Selecting a column subset.

Aggregates and grouped queries

count(), sum(), avg(), min() and max() on a field build aggregates for the dict selector, also across a relation (post.author.id.count()). An aggregate-only projection returns one record; adding plain fields groups by them. Result types are the same on every backend:

Aggregate Takes Returns On no rows
count() any column int 0
sum() a numeric column the column's type None
avg() a numeric column float for int and float, Decimal for Decimal None
min(), max() a numeric, text or date/time column the column's type None

See Aggregations and grouped queries.

Builders

Query

Query(model_cls: Type[T], using: str | None = None, session: Any | None = None)

Bases: Generic[T]

A lazy query over one model's rows.

Start one from the model with Model.where or Model.select. Each chained method returns a new query and leaves the original unchanged; nothing runs until you await all, first, count, exists, update or delete. See Queries.

Examples:

query = Post.where(lambda post: post.views > 900)
newest_first = query.order_by(lambda post: post.id, "desc")

posts = await newest_first.all()
assert [post.id for post in posts] == [2, 1]
assert await query.count() == 2

Parameters:

Name Type Description Default
model_cls Type[T]

The model class whose table the query reads.

required
using str | None

The named connection to run on. Defaults to None, the session's connection.

None
session Any | None

The session to run in. Defaults to None, the session opened by the enclosing async with engines.session():.

None

Methods:

Name Description
where

Add a condition that every returned row must meet.

select

Return only some columns, as records, or the query unchanged.

order_by

Sort the results by a column, after any sort keys added before.

join

Join a related model with INNER JOIN, keeping only rows that have it.

left_join

Join a related model with LEFT JOIN, keeping rows that lack it.

include

Load a related model with each result, in the same query.

limit

Return at most value rows.

offset

Skip the first value rows.

position_of

Read an instance's values for this query's sort keys.

after

Start the results just after a position in the query's order.

before

End the results just before a position in the query's order.

all

Run the query and return every matching record.

count

Count the matching rows.

update

Update every matching row in one statement.

first

Run the query and return its first record, or None when nothing matches.

delete

Delete every matching row in one statement.

exists

Return whether any row matches.

Attributes:

Name Type Description
model_cls

The model class whose rows the query returns.

where_clause list[QueryNode]

The conditions added by where(), combined with AND.

order_by_clause list[OrderByEntry]

The sort keys added by order_by(), in the order added.

model_cls instance-attribute

model_cls = model_cls

The model class whose rows the query returns.

where_clause instance-attribute

where_clause: list[QueryNode] = []

The conditions added by where(), combined with AND.

order_by_clause instance-attribute

order_by_clause: list[OrderByEntry] = []

The sort keys added by order_by(), in the order added.

where

where(predicate: Predicate[T]) -> Self

Add a condition that every returned row must meet.

The lambda receives a stand-in for one row, a QueryProxy; comparing its fields builds the SQL condition. Conditions from several where() calls are combined with AND. A field name the model does not declare raises AttributeError with the closest match, before any SQL runs.

A field that is a forward relation reaches into the related model (lambda post: post.author.name == "Ada Lovelace"), and each relation path adds one INNER JOIN. See Querying across relationships.

Parameters:

Name Type Description Default
predicate Predicate[T]

A lambda that takes the row stand-in and returns a condition, such as lambda post: post.views > 1000.

required

Returns:

Type Description
Self

A new query with the condition added.

Raises:

Type Description
TypeError

predicate is not callable or does not return a condition.

AttributeError

The lambda names a field the model does not have.

Examples:

posts = await Post.where(lambda post: post.author.name == "Grace Hopper").all()
assert [post.title for post in posts] == ["The Education of a Computer"]

select

select() -> Self
select(selector: RowSelector[T]) -> ProjectedQuery[T]
select(*columns: str) -> ProjectedQuery[T]
select(*selectors: RowSelector[T] | str) -> Self | ProjectedQuery[T]

Return only some columns, as records, or the query unchanged.

With no argument, select() returns the same query of whole model instances. With a lambda or column names, the query returns Row records in a Rows list, never model instances. The lambda returns one field, a tuple of fields, or a dict whose keys name the output fields; a field may reach into a related model (post.author.name). Column names as strings name the model's own columns only. See Selecting a column subset.

Parameters:

Name Type Description Default
*selectors RowSelector[T] | str

Nothing; one lambda returning a field, a tuple of fields or a dict naming them; or column names as strings.

()

Returns:

Type Description
Self | ProjectedQuery[T]

The query unchanged with no selector, otherwise a ProjectedQuery.

Raises:

Type Description
AttributeError

A selector names a column the model does not have.

TypeError

The selectors mix a lambda with column names, select a relation or a comparison instead of a field, or nest a dict and a tuple.

ValueError

The selection is empty, two fields share an output name, a string names a related column, or the query already has an include().

Examples:

A tuple keeps each field's own name:

rows = await Post.select(lambda post: (post.title, post.views)).order_by(lambda post: post.id).all()
assert rows[0].title == "Notes on the Analytical Engine"
assert rows[0].views == 1843

A dict names the output fields, and may reach into a related model:

rows = await Post.select(
    lambda post: {"post": post.title, "author": post.author.name}
).order_by(lambda post: post.id).all()
assert rows[1].author == "Grace Hopper"

order_by

order_by(field: str | Callable[[QueryProxy[T]], FieldProxy[Any]], direction: str = 'asc', *, nulls: str | None = None) -> Self

Sort the results by a column, after any sort keys added before.

Name the column with a lambda, the documented form, or a string. Only the lambda can sort by a related model's column (lambda post: post.author.name), which joins that model the way where() does; a string always names a column of the model itself. See Ordering, limit & offset.

Parameters:

Name Type Description Default
field str | Callable[[QueryProxy[T]], FieldProxy[Any]]

A lambda returning the column, such as lambda post: post.views, or the column's name.

required
direction str

"asc" (the default) or "desc".

'asc'
nulls str | None

Where NULL values sort: "first", "last" or "native", the database's own rule. Defaults to None, which sorts them last on every database.

None

Returns:

Type Description
Self

A new query with the sort key added.

Raises:

Type Description
AttributeError

The column is not one the model has.

TypeError

The lambda returns a relation or anything else that is not a column.

ValueError

direction or nulls has a value not listed above.

Examples:

posts = await Post.select().order_by(lambda post: post.views, "desc").all()
assert [post.views for post in posts] == [1843, 952]

join

join(selector: Callable[[QueryProxy[T]], Any]) -> Self

Join a related model with INNER JOIN, keeping only rows that have it.

The lambda names a forward relation, not a column on it. On a nullable relation, a join() with no condition drops the rows whose relation is empty. A where() or order_by() that reaches into the same relation shares the join. See Join type for traversed relations.

Parameters:

Name Type Description Default
selector Callable[[QueryProxy[T]], Any]

A lambda returning a relation, such as lambda post: post.author, or a longer path through several.

required

Returns:

Type Description
Self

A new query with the join added.

Raises:

Type Description
TypeError

selector is not callable, or names a column or a reverse relation instead of a forward relation.

ValueError

A left_join already marked part of the path.

Examples:

query = Post.select().join(lambda post: post.author)
assert await query.count() == 2

left_join

left_join(selector: Callable[[QueryProxy[T]], Any]) -> Self

Join a related model with LEFT JOIN, keeping rows that lack it.

Every relation along the path is joined with LEFT JOIN, so a row missing the relation at any step is still returned, and a field read through the relation is None. The LEFT JOIN also applies to a where(), order_by() or select() that reaches into the same path. See Keeping rows that have no relation.

Parameters:

Name Type Description Default
selector Callable[[QueryProxy[T]], Any]

A lambda returning a relation, such as lambda post: post.author, or a longer path through several.

required

Returns:

Type Description
Self

A new query with the join added.

Raises:

Type Description
TypeError

selector is not callable, or names a column or a reverse relation instead of a forward relation.

ValueError

A join already marked part of the path.

Examples:

rows = await (
    Post.select(lambda post: {"post": post.title, "author": post.author.name})
    .left_join(lambda post: post.author)
    .order_by(lambda post: post.id)
    .all()
)
assert [row.author for row in rows] == ["Ada Lovelace", "Grace Hopper"]

include

include(selector: Callable[[QueryProxy[T]], Any]) -> Self

Load a related model with each result, in the same query.

Each returned instance has the relation filled in: reading it is a plain attribute that holds the related instance, with no await and no second query. include() never changes which rows come back or how many. A path through several relations fills in each one. See Loading relations with include().

Parameters:

Name Type Description Default
selector Callable[[QueryProxy[T]], Any]

A lambda returning a forward relation, such as lambda post: post.author.

required

Returns:

Type Description
Self

A new query that loads the relation.

Raises:

Type Description
TypeError

selector is a string or not callable, or names a column or a reverse or many-to-many relation.

Examples:

posts = await Post.select().include(lambda post: post.author).order_by(lambda post: post.id).all()
assert posts[0].author.name == "Ada Lovelace"

limit

limit(value: int) -> Self

Return at most value rows.

Parameters:

Name Type Description Default
value int

The largest number of rows to return.

required

Returns:

Type Description
Self

A new query with the limit set.

Examples:

posts = await Post.select().order_by(lambda post: post.id).limit(1).all()
assert [post.id for post in posts] == [1]

offset

offset(value: int) -> Self

Skip the first value rows.

For pages deep into a large table, after stays fast where an offset grows slower with every skipped row. See Pagination.

Parameters:

Name Type Description Default
value int

The number of rows to skip.

required

Returns:

Type Description
Self

A new query with the offset set.

Raises:

Type Description
ValueError

after() or before() is already set; a query has one starting point.

Examples:

posts = await Post.select().order_by(lambda post: post.id).offset(1).all()
assert [post.id for post in posts] == [2]

position_of

position_of(row: T) -> tuple[Any, ...]

Read an instance's values for this query's sort keys.

The tuple is the instance's place in the query's order, the cursor that after and before take. Store it to resume paging later, for example in an API's next-page token.

Parameters:

Name Type Description Default
row T

An instance of the queried model.

required

Returns:

Type Description
tuple[Any, ...]

One value per sort key, in the order the keys were added.

Raises:

Type Description
TypeError

row is not an instance of the queried model.

ValueError

The sort keys do not include the primary key, or a key reaches into a relation the instance does not have loaded with include().

Examples:

by_views = Post.select().order_by(lambda post: post.views, "desc").order_by(lambda post: post.id)
top = await by_views.first()
assert by_views.position_of(top) == (1843, 1)

after

after(position: tuple[Any, ...] | T) -> Self

Start the results just after a position in the query's order.

This is keyset paging: pass the last row of one page to get the next. The position is excluded, and rows inserted or deleted elsewhere do not shift the page. The sort keys must include the primary key, so that no two rows share a position. See Keyset (cursor) pagination.

Parameters:

Name Type Description Default
position tuple[Any, ...] | T

An instance of the queried model, or the tuple of its sort-key values that position_of returns. Any value but the primary key's may be None.

required

Returns:

Type Description
Self

A new query that starts after position.

Raises:

Type Description
TypeError

position is neither a tuple nor an instance of the queried model.

ValueError

The sort keys do not include the primary key, the tuple has the wrong length, its primary key value is None, or offset() or before() is already set.

Examples:

by_views = Post.select().order_by(lambda post: post.views, "desc").order_by(lambda post: post.id).limit(1)

page = await by_views.all()
assert [post.views for post in page] == [1843]

next_page = await by_views.after(page[-1]).all()
assert [post.views for post in next_page] == [952]

before

before(position: tuple[Any, ...] | T) -> Self

End the results just before a position in the query's order.

With a limit, this is the previous page, still in the query's order. Without one, it is every row before the position. The position is excluded, and the sort keys must include the primary key, as for after.

Parameters:

Name Type Description Default
position tuple[Any, ...] | T

An instance of the queried model, or the tuple of its sort-key values that position_of returns. Any value but the primary key's may be None.

required

Returns:

Type Description
Self

A new query that ends before position.

Raises:

Type Description
TypeError

position is neither a tuple nor an instance of the queried model.

ValueError

The sort keys do not include the primary key, the tuple has the wrong length, its primary key value is None, or offset() or after() is already set.

Note

Without a limit, first returns the row just before the position, while all()[0] is the first row of the query.

Examples:

by_views = Post.select().order_by(lambda post: post.views, "desc").order_by(lambda post: post.id).limit(1)

previous_page = await by_views.before((952, 2)).all()
assert [post.views for post in previous_page] == [1843]

all async

all() -> list[T]

Run the query and return every matching record.

Returns:

Type Description
list[T]

The matching instances, in the query's order.

Examples:

posts = await Post.where(lambda post: post.views > 1000).all()
assert [post.title for post in posts] == ["Notes on the Analytical Engine"]

count async

count() -> int

Count the matching rows.

Limits and offsets are ignored: the count covers every row the conditions match.

Returns:

Type Description
int

The number of matching rows.

Examples:

assert await Post.where(lambda post: post.views > 900).count() == 2

update async

update(recipe: Callable[[QueryProxy[T]], dict[str, Any]] | None = None, /, **fields: Any) -> int

Update every matching row in one statement.

Pass the new values as keywords, or pass one lambda, a recipe, that returns a dict of new values computed in the database. A recipe value is a literal, another column of the row, + or - arithmetic on columns, now for the database's clock, or .merge() on a JSON column (Postgres only). NULL + 1 is NULL. The two forms cannot be mixed. See Expression updates.

Parameters:

Name Type Description Default
recipe Callable[[QueryProxy[T]], dict[str, Any]] | None

An optional recipe: a lambda that takes the row stand-in and returns a dict of column names to new values. It is positional only, so recipe= as a keyword still names a column.

None
**fields Any

Column names and the literal values to write.

{}

Returns:

Type Description
int

The number of rows updated.

Raises:

Type Description
TypeError

Both forms are given, the recipe is not callable or does not return a dict, or a keyword value is not a literal.

ValueError

The recipe assigns nothing, the query has a limit(), offset(), after() or before(), or it reaches into a related model.

Examples:

Keywords write literal values:

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

A recipe computes each row's new value from its current one:

await Post.where(lambda post: post.views > 900).update(lambda post: {"views": post.views + 1})
posts = await Post.select().order_by(lambda post: post.id).all()
assert [post.views for post in posts] == [1844, 953]

first async

first() -> T | None

Run the query and return its first record, or None when nothing matches.

Returns:

Type Description
T | None

The first matching instance in the query's order, or None.

Examples:

post = await Post.select().order_by(lambda post: post.views).first()
assert post.title == "The Education of a Computer"

delete async

delete() -> int

Delete every matching row in one statement.

Returns:

Type Description
int

The number of rows deleted.

Raises:

Type Description
ValueError

The query has a limit(), offset(), after() or before(), or reaches into a related model through where(), join() or left_join(). Filter on the model's own columns instead, such as the foreign key column author_id.

Examples:

deleted = await Post.where(lambda post: post.views < 1000).delete()
assert deleted == 1

exists async

exists() -> bool

Return whether any row matches.

Returns:

Type Description
bool

True when at least one row matches, otherwise False.

Examples:

assert await Author.where(lambda author: author.email == "ada@example.com").exists()

RenderedSql dataclass

RenderedSql(sql: str, params: tuple[object, ...], dialect: Literal['postgres', 'sqlite'])

One statement a query terminal would send, as the statement log records it.

str() of it is the SQL alone, so print(rendered) shows the statement.

Examples:

rendered = await Author.where(lambda author: author.id == 1).all.sql()
print(rendered.dialect, rendered.params)

Attributes:

Name Type Description
sql str

The SQL text, with the dialect's placeholders ($1 or ?).

params tuple[object, ...]

The bound values in placeholder order, a secret value shown as REDACTED.

dialect Literal['postgres', 'sqlite']

The dialect of the database the call would run on.

sql instance-attribute

sql: str

The SQL text, with the dialect's placeholders ($1 or ?).

params instance-attribute

params: tuple[object, ...]

The bound values in placeholder order, a secret value shown as REDACTED.

dialect instance-attribute

dialect: Literal['postgres', 'sqlite']

The dialect of the database the call would run on.

REDACTED module-attribute

REDACTED: Final = _Redacted()

A secret parameter as a record shows it: its repr and str are ***.

Terminal

Terminal(method: Callable[..., Awaitable[R_co]], query: object)

Bases: Generic[P, R_co]

A query terminal bound to its query: awaiting a call runs it, .sql() renders it.

Methods:

Name Description
sql

Render the statement this terminal would send, without sending it.

sql async

sql(*args: args, **kwargs: kwargs) -> RenderedSql

Render the statement this terminal would send, without sending it.

Takes exactly the arguments the terminal takes and routes like the call: the enclosing session, using= and session= pick the database. On Postgres it may read the table's column types once, the way the call would; it never sends the statement itself, opens no transaction and changes no row.

Parameters:

Name Type Description Default
*args args

The terminal's positional arguments.

()
**kwargs kwargs

The terminal's keyword arguments.

{}

Returns:

Type Description
RenderedSql

The SQL, parameters and dialect the call would send, as the statement log records them, with each secret value shown as REDACTED.

Raises:

Type Description
RuntimeError

No database route: the call is outside a session and no connection was named.

TypeError

The arguments are ones the terminal rejects.

Examples:

rendered = await Author.where(lambda author: author.id == 1).all.sql()
print(rendered)

ProjectedQuery

ProjectedQuery(source: Query[T], fields: tuple[_ProjectedField, ...])

Bases: Query[T]

A query that returns some columns as records, not model instances.

select with a lambda or column names returns one. Awaiting all gives Row records in a Rows list. Records are plain values: they are not tracked by the session and cannot be saved. Filtering, sorting and paging work as on any query.

A dict selector whose values include an aggregate such as post.views.sum() groups the rows by the plain fields beside it. See Aggregations and grouped queries.

Examples:

rows = await Post.select(
    lambda post: {"author": post.author.name, "total_views": post.views.sum()}
).order_by("author").all()
assert [(row.author, row.total_views) for row in rows] == [
    ("Ada Lovelace", 1843),
    ("Grace Hopper", 952),
]

Parameters:

Name Type Description Default
source Query[T]

The query to project. It is left unchanged.

required
fields tuple[_ProjectedField, ...]

The fields to return, in order.

required

Raises:

Type Description
ValueError

A sort key added before the projection is not one of its group keys.

Methods:

Name Description
order_by

Sort the records by an output field, a column or an aggregate.

count

Count the matching rows, whatever columns the projection selects.

exists

Return whether any row matches, whatever columns the projection selects.

position_of

Read a record's values for this query's sort keys.

all

Run the query and return a record for every matching row, or group.

first

Run the query and return its first record, or None when nothing matches.

select

Refuse a second select(), which would change the result type mid-chain.

include

Refuse include(): a record is flat and cannot hold a related instance.

update

Refuse update(): a projection only reads.

delete

Refuse delete(): a projection only reads.

order_by

order_by(field: str | Callable[[QueryProxy[T]], Any], direction: str = 'asc', *, nulls: str | None = None) -> Self

Sort the records by an output field, a column or an aggregate.

A string names an output field first and a column of the model second, the way SQL's ORDER BY reads names. A lambda names a column, which may reach into a related model, or an aggregate that the projection returns, such as lambda post: post.views.sum().

When the projection has an aggregate, every sort key must be a group key or an aggregate: any other column has no single value per group. See Ordering grouped results.

Parameters:

Name Type Description Default
field str | Callable[[QueryProxy[T]], Any]

An output field or column name, or a lambda returning a column or an aggregate.

required
direction str

"asc" (the default) or "desc".

'asc'
nulls str | None

Where NULL values sort: "first", "last" or "native", the database's own rule. Defaults to None, which sorts them last on every database.

None

Returns:

Type Description
Self

A new query with the sort key added.

Raises:

Type Description
ValueError

direction or nulls has a value not listed above, or on an aggregate projection the key is neither a group key nor an aggregate the projection returns.

AttributeError

A string names neither an output field nor a column of the model.

TypeError

The lambda returns a relation or anything else that is not a column or an aggregate.

Examples:

rows = await Post.select(
    lambda post: {"author": post.author.name, "total_views": post.views.sum()}
).order_by(lambda post: post.views.sum(), "desc").all()
assert [row.author for row in rows] == ["Ada Lovelace", "Grace Hopper"]

count

count() -> Awaitable[int]

Count the matching rows, whatever columns the projection selects.

On a projection with an aggregate, "count" could mean rows or groups, so the call raises before any SQL runs.

Returns:

Type Description
int

The number of matching rows, once awaited.

Raises:

Type Description
ValueError

The projection has an aggregate. Count rows with the query before select(), or groups with len(await query.all()).

Examples:

assert await Post.select(lambda post: post.title).count() == 2

exists

exists() -> Awaitable[bool]

Return whether any row matches, whatever columns the projection selects.

On a projection with only aggregates there is always exactly one record, so the call raises before any SQL runs.

Returns:

Type Description
bool

True when at least one row matches, once awaited.

Raises:

Type Description
ValueError

The projection has an aggregate. Test rows with the query before select(), or groups with len(await query.all()) > 0.

position_of

position_of(row: T | Row) -> tuple[Any, ...]

Read a record's values for this query's sort keys.

Every sort key must be among the selected fields, under its own name or an output name. Otherwise build the tuple yourself for after() or before().

Parameters:

Name Type Description Default
row T | Row

A record this query returned, or an instance of the queried model.

required

Returns:

Type Description
tuple[Any, ...]

One value per sort key, in the order the keys were added.

Raises:

Type Description
TypeError

row is neither a Row nor an instance of the queried model.

ValueError

A sort key is not selected, the sort keys do not include the primary key, or a key reaches into a relation the instance does not have loaded.

Examples:

by_views = Post.select(lambda post: (post.id, post.views)).order_by(lambda post: post.views, "desc").order_by(lambda post: post.id)
top = await by_views.first()
assert by_views.position_of(top) == (1843, 1)

all async

all() -> Rows[Row]

Run the query and return a record for every matching row, or group.

Returns:

Type Description
Rows[Row]

A Rows list of Row records, each with the selected fields in selection order.

Examples:

rows = await Post.select(lambda post: post.views).order_by(lambda post: post.id).all()
assert [row.views for row in rows] == [1843, 952]

first async

first() -> Row | None

Run the query and return its first record, or None when nothing matches.

Returns:

Type Description
Row | None

The first Row in the query's order, or None.

Examples:

row = await Post.select(lambda post: post.title).order_by(lambda post: post.views).first()
assert row.title == "The Education of a Computer"

select

select(*selectors: RowSelector[T] | str) -> NoReturn

Refuse a second select(), which would change the result type mid-chain.

Parameters:

Name Type Description Default
*selectors RowSelector[T] | str

Ignored; the call always raises.

()

Raises:

Type Description
ValueError

Always. Select every field in one select() call, or start a new query from the model.

include

include(selector: Any) -> NoReturn

Refuse include(): a record is flat and cannot hold a related instance.

A type checker reports the call as an error too. To read a related model's columns, select them through the relation (lambda post: {"author": post.author.name}).

Parameters:

Name Type Description Default
selector Any

Ignored; the call always raises.

required

Raises:

Type Description
ValueError

Always. Select the related columns, or call include() on a query without select().

update

update(recipe: Callable[..., Any] | None = None, /, **fields: Any) -> NoReturn

Refuse update(): a projection only reads.

A type checker reports the call as an error too.

Parameters:

Name Type Description Default
recipe Callable[..., Any] | None

Ignored; the call always raises.

None
**fields Any

Ignored; the call always raises.

{}

Raises:

Type Description
ValueError

Always. Update through a query without select(), such as Model.where(...).update(...).

delete

delete() -> NoReturn

Refuse delete(): a projection only reads.

A type checker reports the call as an error too.

Raises:

Type Description
ValueError

Always. Delete through a query without select(), such as Model.where(...).delete().

Predicates

QueryProxy

QueryProxy(model_cls: type, *, root: str | None = None)

Bases: Generic[TModel]

The stand-in for one row that a query lambda receives.

Reading a field gives a FieldProxy for that column, so lambda post: post.views > 1000 builds a condition. A misspelled name raises AttributeError with the closest match, before any SQL runs. A forward relation gives a stand-in for the related row (post.author.name), and a reverse or many-to-many relation offers exists() (author.posts.exists()). See Typed query predicates.

Examples:

authors = await Author.where(lambda author: author.posts.exists(lambda post: post.views > 1000)).all()
assert [author.name for author in authors] == ["Ada Lovelace"]

Parameters:

Name Type Description Default
model_cls type

The queried model class.

required
root str | None

The name of the lambda parameter this stand-in is passed as, which error messages spell the row with. Defaults to None, the model's name in snake case.

None

Predicate module-attribute

Predicate: TypeAlias = Callable[[QueryProxy[TModel]], QueryNode]

The type of a query lambda: it takes a row stand-in and returns a condition.

Predicate[Post] is Callable[[QueryProxy[Post]], QueryNode], as in lambda post: post.views > 1000.

FieldProxy

FieldProxy(column: str, path: tuple[str, ...] = (), owner: type | None = None, *, root: str | None = None)

Bases: Generic[TField]

A reference to one column inside a query lambda.

Reading a field from the lambda's parameter gives one: post.views in lambda post: post.views > 1000. It builds:

  • conditions, with ==, !=, <, <=, >, >=, in_ (or <<) and like;
  • aggregates for a select() dict, with count, sum, avg, min and max;
  • new values in an update() recipe, with +, - and merge.

The type parameter is the column's Python type, so a type checker can tell, for example, that like needs a text column.

Examples:

posts = await Post.where(lambda post: post.views >= 952).all()
assert [post.id for post in posts] == [1, 2]

Parameters:

Name Type Description Default
column str

The column's name.

required
path tuple[str, ...]

The relation fields from the queried model to the column's model. Defaults to (), the queried model itself.

()
owner type | None

The model the column belongs to. Defaults to None, which skips the column type checks of the aggregate methods.

None
root str | None

The lambda parameter the column was read from, as error messages spell it. Defaults to None: the owner's name in snake case when path is empty, otherwise left out.

None

Methods:

Name Description
count

Count the rows where this column is not NULL, as SQL COUNT(column).

sum

Add up a numeric column, as SQL SUM(column).

avg

Average a numeric column, as SQL AVG(column).

min

Find a column's smallest value, as SQL MIN(column).

max

Find a column's largest value, as SQL MAX(column).

in_

Match a column against a list of values, as SQL IN.

like

Match a text column against a pattern, as SQL LIKE.

merge

Merge keys into a JSON object column in an update() recipe (Postgres only).

Attributes:

Name Type Description
column

The column's name.

path

The relation fields from the queried model to the column's model.

column instance-attribute

column = column

The column's name.

path instance-attribute

path = path

The relation fields from the queried model to the column's model.

count

count() -> AggregateExpr

Count the rows where this column is not NULL, as SQL COUNT(column).

Returns:

Type Description
AggregateExpr

An aggregate to name in a select() dict. Its value is an int, 0 over no rows.

Examples:

row = await Post.select(lambda post: {"posts": post.id.count()}).first()
assert row.posts == 2

sum

sum() -> AggregateExpr

Add up a numeric column, as SQL SUM(column).

Returns:

Type Description
AggregateExpr

An aggregate to name in a select() dict. Its value has the column's type, or is None over no rows.

Raises:

Type Description
TypeError

The column is not an int, float or Decimal column.

Examples:

row = await Post.select(lambda post: {"total": post.views.sum()}).first()
assert row.total == 2795

avg

avg() -> AggregateExpr

Average a numeric column, as SQL AVG(column).

Returns:

Type Description
AggregateExpr

An aggregate to name in a select() dict. Its value is a float, or a Decimal for a Decimal column, or None over no rows.

Raises:

Type Description
TypeError

The column is not an int, float or Decimal column.

Examples:

row = await Post.select(lambda post: {"mean": post.views.avg()}).first()
assert row.mean == 1397.5

min

min() -> AggregateExpr

Find a column's smallest value, as SQL MIN(column).

Returns:

Type Description
AggregateExpr

An aggregate to name in a select() dict. Its value has the column's type, or is None over no rows.

Raises:

Type Description
TypeError

The column is not a number, text, date or time column.

Examples:

row = await Post.select(lambda post: {"low": post.views.min()}).first()
assert row.low == 952

max

max() -> AggregateExpr

Find a column's largest value, as SQL MAX(column).

Returns:

Type Description
AggregateExpr

An aggregate to name in a select() dict. Its value has the column's type, or is None over no rows.

Raises:

Type Description
TypeError

The column is not a number, text, date or time column.

Examples:

row = await Post.select(lambda post: {"high": post.views.max()}).first()
assert row.high == 1843

in_

in_(other: list[TField] | tuple[TField, ...] | set[TField]) -> QueryNode

Match a column against a list of values, as SQL IN.

post.id << {2, 3} is the same condition. To test membership in related rows, use the relation's exists() instead of a subquery.

Parameters:

Name Type Description Default
other list[TField] | tuple[TField, ...] | set[TField]

The values to match, as a list, tuple or set.

required

Returns:

Type Description
QueryNode

A condition met when the column equals one of the values.

Raises:

Type Description
TypeError

other is not a list, tuple or set; a query is refused with a pointer to exists().

Examples:

posts = await Post.where(lambda post: post.id.in_([2, 3])).all()
assert [post.id for post in posts] == [2]

like

like(pattern: str) -> QueryNode

Match a text column against a pattern, as SQL LIKE.

In the pattern, % matches any run of characters and _ one character. A type checker accepts like on text columns only.

Parameters:

Name Type Description Default
pattern str

The pattern, such as "%Engine%".

required

Returns:

Type Description
QueryNode

A condition met when the column matches.

Examples:

posts = await Post.where(lambda post: post.title.like("%Engine%")).all()
assert [post.id for post in posts] == [1]

merge

merge(patch: Any) -> MergeValueExpr

Merge keys into a JSON object column in an update() recipe (Postgres only).

The update renders Postgres jsonb ||: keys in patch replace the same keys in the column, other keys stay, and a NULL column counts as {}. The merge is shallow, so a nested object in patch replaces the stored one whole. For example, Post.where(...).update(lambda post: {"meta": post.meta.merge({"pinned": True})}) sets one key of a meta JSON column.

Parameters:

Name Type Description Default
patch Any

The keys and values to merge in, as a mapping.

required

Returns:

Type Description
MergeValueExpr

A new value for the column, to assign in an update() recipe.

Raises:

Type Description
TypeError

patch is not a mapping, or the column does not hold a JSON object (a list column, or any other type).

RelationProxy

RelationProxy(root_model: type, path: tuple[str, ...], target: type, *, root: str | None = None)

The stand-in for a related row, reached through a forward relation.

post.author in a query lambda gives one. Reading a field from it reaches into the related model (post.author.name) and joins that model when the query runs; the path can continue through further relations. Comparing the relation itself with == or != to a saved instance or None compares the foreign key column, with no join. Other comparisons on the relation itself raise TypeError naming a column to compare instead.

Examples:

ada = await Author.get(1)
by_ada = await Post.where(lambda post: post.author == ada).all()
assert [post.id for post in by_ada] == [1]

by_name = await Post.where(lambda post: post.author.name == "Grace Hopper").all()
assert [post.id for post in by_name] == [2]

Parameters:

Name Type Description Default
root_model type

The queried model class.

required
path tuple[str, ...]

The relation fields from the queried model to this one.

required
target type

The related model class.

required
root str | None

The lambda parameter the relation was read from, as error messages spell it. Defaults to None, the queried model's name in snake case.

None

Methods:

Name Description
in_

Refuse in_ on a relation; compare one of its columns instead.

like

Refuse like on a relation; match one of its columns instead.

in_

in_(other: object) -> QueryNode

Refuse in_ on a relation; compare one of its columns instead.

Parameters:

Name Type Description Default
other object

Ignored; the call always raises.

required

Raises:

Type Description
TypeError

Always.

like

like(other: object) -> QueryNode

Refuse like on a relation; match one of its columns instead.

Parameters:

Name Type Description Default
other object

Ignored; the call always raises.

required

Raises:

Type Description
TypeError

Always.

QueryNode

QueryNode(column: str | None = None, operator: str | None = None, value: Any = None, left: QueryNode | None = None, right: QueryNode | None = None, is_compound: bool = False, path: tuple[str, ...] = (), child: QueryNode | None = None, exists: ExistsTest | None = None, owner: type | None = None)

A condition in a query: one comparison, or several combined.

A comparison in a query lambda returns one, such as post.views > 1000. Combine conditions with & (and) and | (or), and negate one with ~, which renders SQL NOT (...). Python's own and, or and not raise TypeError, since they would keep only one side. A negated comparison, like SQL NOT, leaves out rows where the column is NULL; see Negation and NULL values.

Examples:

posts = await Post.where(
    lambda post: (post.views > 1000) | (post.title == "The Education of a Computer")
).all()
assert [post.id for post in posts] == [1, 2]

quiet = await Post.where(lambda post: ~(post.views > 1000)).all()
assert [post.id for post in quiet] == [2]

Parameters:

Name Type Description Default
column str | None

The compared column, on a comparison.

None
operator str | None

The comparison ("==", "<", "IN", "LIKE", ...), or "AND" or "OR" on a combination.

None
value Any

The value the column is compared with.

None
left QueryNode | None

The first condition of a combination.

None
right QueryNode | None

The second condition of a combination.

None
is_compound bool

Whether the node combines left and right.

False
path tuple[str, ...]

The relation fields from the queried model to the column's model. Defaults to (), the queried model itself.

()
child QueryNode | None

The negated condition, on a ~ node.

None
exists ExistsTest | None

The details of an existence test, on a node built by .exists().

None
owner type | None

The model whose stand-in built the comparison, used to refuse a condition that mixes two lambdas' parameters.

None

Methods:

Name Description
to_ir_dict

Convert the condition to the dict form Ferro sends with a query.

Attributes:

Name Type Description
column

The compared column, or None on a combination.

operator

The comparison or combining operator.

value

The value the column is compared with.

left

The first condition of a combination.

right

The second condition of a combination.

is_compound

Whether the node combines left and right.

path

The relation fields from the queried model to the column's model.

child

The negated condition, on a ~ node.

exists

The details of an existence test, on a node built by .exists().

owner

The model whose stand-in built the comparison, when known.

column instance-attribute

column = column

The compared column, or None on a combination.

operator instance-attribute

operator = operator

The comparison or combining operator.

value instance-attribute

value = value

The value the column is compared with.

left instance-attribute

left = left

The first condition of a combination.

right instance-attribute

right = right

The second condition of a combination.

is_compound instance-attribute

is_compound = is_compound

Whether the node combines left and right.

path instance-attribute

path = path

The relation fields from the queried model to the column's model.

child instance-attribute

child = child

The negated condition, on a ~ node.

exists instance-attribute

exists = exists

The details of an existence test, on a node built by .exists().

owner instance-attribute

owner = owner

The model whose stand-in built the comparison, when known.

to_ir_dict

to_ir_dict() -> dict[str, Any]

Convert the condition to the dict form Ferro sends with a query.

Returns:

Type Description
dict[str, Any]

The condition and everything under it, as plain dicts and lists.

ValueExpr

A new value computed in the database, for an update() recipe.

post.views + 1, now and .merge() build one. Assign it to a column in the dict an update() recipe returns. A value expression cannot be compared, selected or sorted by: it is only a new value.

Examples:

await Post.where(lambda post: post.id == 1).update(lambda post: {"views": post.views + 1})
assert (await Post.get(1)).views == 1844

Projections

Row

Bases: BaseModel

One record from a select() projection: the selected fields, by name.

A Row is not a model instance: it has no save() or refresh(), the session does not track it, and its fields are the ones the projection selected, in that order. Reading a field, model_dump(), model_dump_json(), equality and repr work as on any Pydantic model. See Selecting a column subset.

Examples:

rows = await Post.select(lambda post: (post.id, post.views)).order_by(lambda post: post.id).all()
assert rows[0].views == 1843
assert rows[0].model_dump() == {"id": 1, "views": 1843}

Rows

Bases: RootModel[list[R]]

The list of records a projected query's all() returns.

It works like a list: indexing, slicing (which returns a Rows), iteration, len() and truthiness. As a Pydantic RootModel, model_dump() gives a list of dicts and Rows[Row] works as a FastAPI response_model.

Examples:

rows = await Post.select(lambda post: (post.id, post.title)).order_by(lambda post: post.id).all()
assert len(rows) == 2
assert rows[:1].model_dump() == [{"id": 1, "title": "Notes on the Analytical Engine"}]

RowSelector module-attribute

RowSelector: TypeAlias = Callable[[QueryProxy[TModel]], FieldProxy[Any] | tuple[FieldProxy[Any], ...] | list[FieldProxy[Any]] | dict[str, 'FieldProxy[Any] | AggregateExpr']]

The type of a select() lambda: it takes a row stand-in and returns the fields to keep.

It returns one field (lambda post: post.title), a tuple of fields (lambda post: (post.id, post.title)), or a dict whose string keys name the output fields (lambda post: {"author": post.author.name}). A field may be reached through relations, and a dict value may be an aggregate ({"total": post.views.sum()}). A type checker refuses a comparison, a nested shape or a key that is not a string.

AggregateExpr

AggregateExpr(fn: str, column: str, path: tuple[str, ...], *, root: str | None = None)

An aggregate over one column, such as post.views.sum(), for a select() dict.

Name each aggregate with a dict key: select(lambda post: {"total": post.views.sum()}). The column may be reached through a relation (post.author.id.count()). With only aggregates, the query returns one record; with plain fields beside them, one record per group of those fields. See Aggregations and grouped queries.

An aggregate cannot be compared or used as a condition: where() filters rows before they are aggregated, and Ferro has no having() for filtering groups. Filter the rows with where(), or compare the aggregated results in Python.

Examples:

row = await Post.select(lambda post: {"total": post.views.sum()}).first()
assert row.total == 2795

Parameters:

Name Type Description Default
fn str

The aggregate: "count", "sum", "avg", "min" or "max".

required
column str

The aggregated column.

required
path tuple[str, ...]

The relation fields from the queried model to the column's model.

required
root str | None

The lambda parameter the column was read from, as error messages spell it. Defaults to None, left out.

None

Attributes:

Name Type Description
fn

The aggregate: "count", "sum", "avg", "min" or "max".

column

The aggregated column.

path

The relation fields from the queried model to the column's model.

fn instance-attribute

fn = fn

The aggregate: "count", "sum", "avg", "min" or "max".

column instance-attribute

column = column

The aggregated column.

path instance-attribute

path = path

The relation fields from the queried model to the column's model.

now module-attribute

now = NowExpr()

The database's clock, for stamping a datetime column in an update() recipe.

Assign now itself, not now(). The update renders SQL CURRENT_TIMESTAMP, so the time comes from the database server, not from Python.

Examples:

from datetime import datetime
from typing import Annotated

from ferro import FerroField, Model, create_tables, now


class Visit(Model):
    id: Annotated[int | None, FerroField(primary_key=True)] = None
    page: str
    seen_at: datetime | None = None


await create_tables()
visit = await Visit.create(page="/about")
await Visit.where(lambda visit: visit.page == "/about").update(lambda visit: {"seen_at": now})
await visit.refresh()
assert visit.seen_at is not None