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 SQLNOT (...): Negation and NULL values.- A lambda that follows a foreign key adds one
INNER JOINper 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 correlatedEXISTS: 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 withinclude().nulls=onorder_by()defaults toNULLS LASTon 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
¶
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
|
session
|
Any | None
|
The session to run in. Defaults to |
None
|
- How-to How to soft-delete rows The SoftDeleteMixin
- Reference Python API
- Reference Python API
- Reference Python API
- Reference Python API
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 |
left_join |
Join a related model with |
include |
Load a related model with each result, in the same query. |
limit |
Return at most |
offset |
Skip the first |
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 |
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 |
order_by_clause |
list[OrderByEntry]
|
The sort keys added by |
where_clause
instance-attribute
¶
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
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new query with the condition added. |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
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
|
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 |
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"
- Guide Queries Selecting a column subset
-
Reference
Python API
Query
ProjectedQuery
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
|
required |
direction
|
str
|
|
'asc'
|
nulls
|
str | None
|
Where |
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
|
|
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
|
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new query with the join added. |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
A |
Examples:
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
|
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new query with the join added. |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
A |
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"]
- Guide Queries Querying across relationships Keeping rows that have no relation
-
Reference
Python API
Query
Queryjoin
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
|
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new query that loads the relation. |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
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
¶
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
¶
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
|
|
Examples:
posts = await Post.select().order_by(lambda post: post.id).offset(1).all()
assert [post.id for post in posts] == [2]
position_of
¶
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
|
|
ValueError
|
The sort keys do not include the primary key, or a
key reaches into a relation the instance does not have loaded
with |
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)
- Guide Queries Paging with after() and before()
- How-to How to paginate query results A paginated API endpoint
-
Reference
Python API
Query
Query
after
¶
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
|
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new query that starts after |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
The sort keys do not include the primary key, the
tuple has the wrong length, its primary key value is |
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]
- Guide Queries Paging with after() and before()
- How-to How to paginate query results
-
Reference
Python API
Query
Query
before
¶
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
|
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new query that ends before |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
The sort keys do not include the primary key, the
tuple has the wrong length, its primary key value is |
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]
- Guide Queries Paging with after() and before()
- How-to How to paginate query results
-
Reference
Python API
Query
Queryposition_of
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:
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:
- Guide Queries Executing queries
-
Reference
Python API
Query
Query
update
async
¶
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 |
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
|
Examples:
Keywords write literal values:
A recipe computes each row's new value from its current one:
first
async
¶
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 |
Examples:
post = await Post.select().order_by(lambda post: post.views).first()
assert post.title == "The Education of a Computer"
- Guide Queries Executing queries
-
Reference
Python API
Query
Querybefore
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 |
Examples:
- How-to How to soft-delete rows See also
-
Reference
Python API
Query
Query
RenderedSql
dataclass
¶
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 ( |
params |
tuple[object, ...]
|
The bound values in placeholder order, a secret value shown as |
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 ***.
- Guide Inspecting SQL Secret columns
- Reference Python API Query
Terminal
¶
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
|
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:
ProjectedQuery
¶
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 |
select |
Refuse a second |
include |
Refuse |
update |
Refuse |
delete |
Refuse |
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'
|
nulls
|
str | None
|
Where |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
A new query with the sort key added. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
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:
count
¶
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 |
Examples:
exists
¶
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
The projection has an aggregate. Test rows with the
query before |
position_of
¶
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
|
|
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:
all
async
¶
Run the query and return a record for every matching row, or group.
Returns:
| Type | Description |
|---|---|
Rows[Row]
|
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]
-
Reference
Python API
Query
ProjectedQuery
first
async
¶
first() -> Row | None
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 |
include
¶
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
|
update
¶
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 |
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 |
Predicates¶
QueryProxy
¶
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
|
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<<) andlike; - aggregates for a
select()dict, withcount,sum,avg,minandmax; - new values in an
update()recipe, with+,-andmerge.
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 |
()
|
owner
|
type | None
|
The model the column belongs to. Defaults to |
None
|
root
|
str | None
|
The lambda parameter the column was read from, as error
messages spell it. Defaults to |
None
|
- Reference Python API Query
Methods:
| Name | Description |
|---|---|
count |
Count the rows where this column is not |
sum |
Add up a numeric column, as SQL |
avg |
Average a numeric column, as SQL |
min |
Find a column's smallest value, as SQL |
max |
Find a column's largest value, as SQL |
in_ |
Match a column against a list of values, as SQL |
like |
Match a text column against a pattern, as SQL |
merge |
Merge keys into a JSON object column in an |
Attributes:
| Name | Type | Description |
|---|---|---|
column |
The column's name. |
|
path |
The relation fields from the queried model to the column's model. |
path
instance-attribute
¶
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 |
Examples:
-
Reference
Python API
Query
FieldProxy
sum
¶
sum() -> AggregateExpr
Add up a numeric column, as SQL SUM(column).
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
An aggregate to name in a |
Raises:
| Type | Description |
|---|---|
TypeError
|
The column is not an |
Examples:
-
Reference
Python API
Query
FieldProxy
avg
¶
avg() -> AggregateExpr
Average a numeric column, as SQL AVG(column).
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
An aggregate to name in a |
Raises:
| Type | Description |
|---|---|
TypeError
|
The column is not an |
Examples:
-
Reference
Python API
Query
FieldProxy
min
¶
min() -> AggregateExpr
Find a column's smallest value, as SQL MIN(column).
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
An aggregate to name in a |
Raises:
| Type | Description |
|---|---|
TypeError
|
The column is not a number, text, date or time column. |
Examples:
-
Reference
Python API
Query
FieldProxy
max
¶
max() -> AggregateExpr
Find a column's largest value, as SQL MAX(column).
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
An aggregate to name in a |
Raises:
| Type | Description |
|---|---|
TypeError
|
The column is not a number, text, date or time column. |
Examples:
-
Reference
Python API
Query
FieldProxy
in_
¶
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
|
|
Examples:
posts = await Post.where(lambda post: post.id.in_([2, 3])).all()
assert [post.id for post in posts] == [2]
-
Reference
Python API
Query
FieldProxy
like
¶
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 |
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]
-
Reference
Python API
Query
FieldProxy
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 |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
-
Reference
Python API
Query
FieldProxy
RelationProxy
¶
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
|
Methods:
| Name | Description |
|---|---|
in_ |
Refuse |
like |
Refuse |
in_
¶
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 ( |
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 |
False
|
path
|
tuple[str, ...]
|
The relation fields from the queried model to the column's
model. Defaults to |
()
|
child
|
QueryNode | None
|
The negated condition, on a |
None
|
exists
|
ExistsTest | None
|
The details of an existence test, on a node built by
|
None
|
owner
|
type | None
|
The model whose stand-in built the comparison, used to refuse a condition that mixes two lambdas' parameters. |
None
|
- Reference Python API Query
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 |
|
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 |
|
path |
The relation fields from the queried model to the column's model. |
|
child |
The negated condition, on a |
|
exists |
The details of an existence test, on a node built by |
|
owner |
The model whose stand-in built the comparison, when known. |
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}
- Concepts Typed query predicates
- Guide Queries Selecting a column subset The Row result type
- Reference Python API
-
Reference
Python API
Query
ProjectedQuery
-
Reference
Python API
Query
ProjectedQueryposition_of
Rows
¶
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"}]
- Concepts Typed query predicates
- Guide Queries Selecting a column subset The Row result type
- Reference Python API Query
-
Reference
Python API
Query
ProjectedQueryall
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.
- Concepts Typed query predicates Reference
AggregateExpr
¶
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:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
str
|
The aggregate: |
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
|
Attributes:
| Name | Type | Description |
|---|---|---|
fn |
The aggregate: |
|
column |
The aggregated column. |
|
path |
The relation fields from the queried model to the column's model. |
now
module-attribute
¶
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