pub struct QuerySet<M: Model> { /* private fields */ }Expand description
Lazy query over model M.
Implementations§
Source§impl<M: Model> QuerySet<M>
impl<M: Model> QuerySet<M>
Sourcepub fn union(self, other: QuerySet<M>) -> Result<Self, QueryError>
pub fn union(self, other: QuerySet<M>) -> Result<Self, QueryError>
Rows in either queryset, duplicates removed (UNION).
Both querysets must project the same columns (same names, same
order). Order and limit the combined result by calling order_by /
limit on the returned queryset; ordering inside other is dropped,
and order_by terms must name output columns.
§Errors
QueryError::InvalidPlan if the projections differ or the querysets
are bound to different databases (see
Db::same_database).
Sourcepub fn union_all(self, other: QuerySet<M>) -> Result<Self, QueryError>
pub fn union_all(self, other: QuerySet<M>) -> Result<Self, QueryError>
Sourcepub fn intersection(self, other: QuerySet<M>) -> Result<Self, QueryError>
pub fn intersection(self, other: QuerySet<M>) -> Result<Self, QueryError>
Sourcepub fn difference(self, other: QuerySet<M>) -> Result<Self, QueryError>
pub fn difference(self, other: QuerySet<M>) -> Result<Self, QueryError>
Source§impl<M: Model> QuerySet<M>
impl<M: Model> QuerySet<M>
Sourcepub fn after(self, token: &str) -> Self
pub fn after(self, token: &str) -> Self
Continue after the position token names (a CursorPage::next).
The last of after and before wins only within
the same direction; asking for both is an error. The token is
checked by cursor_page.
Sourcepub fn before(self, token: &str) -> Self
pub fn before(self, token: &str) -> Self
Page backwards from the position token names (a
CursorPage::previous). See after.
Sourcepub async fn cursor_page(self, limit: u64) -> Result<CursorPage<M>, OrmError>
pub async fn cursor_page(self, limit: u64) -> Result<CursorPage<M>, OrmError>
One page of at most limit rows (at least 1) in a single
statement, without a count.
The ordering is the queryset’s order_by (or the model’s), made
total by appending the primary key. Its terms must be columns of
the model. Nulls sort last ascending and first descending on every
backend. A cursor set with after or
before is validated against this queryset’s
fingerprint: its filters, ordering and table.
§Errors
QueryError::InvalidPlan for limit == 0, a queryset with
distinct, grouping, set operations, limit/offset or row
locks, or an ordering term that is not a model column;
OrmError::Cursor for a rejected token; capability errors
(Redis, and MongoDB with a nullable ordering column) and backend
errors.
Source§impl<M: Model> QuerySet<M>
impl<M: Model> QuerySet<M>
Sourcepub async fn all_annotated(self) -> Result<Vec<(M, Row)>, OrmError>
pub async fn all_annotated(self) -> Result<Vec<(M, Row)>, OrmError>
Like all, pairing each model with its full result row,
so annotated columns can be read with Row::get_as.
§Errors
As all.
Sourcepub async fn get(self, predicate: Expr) -> Result<M, OrmError>
pub async fn get(self, predicate: Expr) -> Result<M, OrmError>
Exactly one row matching predicate.
§Errors
QueryError::DoesNotExist, QueryError::MultipleObjectsReturned,
or as all.
Sourcepub async fn paginate(
self,
page: u64,
per_page: u64,
) -> Result<Page<M>, OrmError>
pub async fn paginate( self, page: u64, per_page: u64, ) -> Result<Page<M>, OrmError>
One page of the queryset (page starts at 1) plus the total count.
The plan is checked against the backend before the count runs.
§Errors
QueryError::InvalidPlan for page == 0 or per_page == 0;
capability or backend errors.
Source§impl<M: Model> QuerySet<M>
impl<M: Model> QuerySet<M>
Load relation’s target in the same query (LEFT JOIN), so
ForeignKey::cached() is filled without further queries. Repeated
calls share joins of a common path (author, then author → team).
Load relation’s targets with one extra query (WHERE pk IN (..))
after the main query, instead of one query per row. Only single-hop
relations can be prefetched; use select_related
for longer paths. Reverse foreign keys and many-to-many relations are
not prefetched (the model has no slot to hold them).
Source§impl<M: Model> QuerySet<M>
impl<M: Model> QuerySet<M>
Sourcepub fn project<S: Into<SelectExpr>>(
self,
fields: impl IntoIterator<Item = S>,
) -> Self
pub fn project<S: Into<SelectExpr>>( self, fields: impl IntoIterator<Item = S>, ) -> Self
Select only fields (Django values() as a builder): the queryset
then yields dynamic rows through rows instead of
models. Fields may be Field / Joined handles (Book::title.select()),
column names, ("name", expr) pairs, or annotation names.
Call project first and annotate after it to group: aggregates
group by the projected columns. The model’s default ordering is
dropped.
Sourcepub async fn values<S: Into<SelectExpr>>(
self,
fields: impl IntoIterator<Item = S>,
) -> Result<Vec<Row>, OrmError>
pub async fn values<S: Into<SelectExpr>>( self, fields: impl IntoIterator<Item = S>, ) -> Result<Vec<Row>, OrmError>
Sourcepub async fn values_list<T: FromValues, S: Into<SelectExpr>>(
self,
fields: impl IntoIterator<Item = S>,
) -> Result<Vec<T>, OrmError>
pub async fn values_list<T: FromValues, S: Into<SelectExpr>>( self, fields: impl IntoIterator<Item = S>, ) -> Result<Vec<T>, OrmError>
fields decoded by position into T, a scalar or tuple (Django
values_list(..)): values_list::<(String, i64)>([..]).
§Errors
QueryError::Decode if a column does not fit T; capability or
backend errors.
Sourcepub async fn aggregate<S: Into<SelectExpr>>(
self,
aggregates: impl IntoIterator<Item = S>,
) -> Result<Row, OrmError>
pub async fn aggregate<S: Into<SelectExpr>>( self, aggregates: impl IntoIterator<Item = S>, ) -> Result<Row, OrmError>
One row of aggregates over the whole queryset (Django aggregate):
aggregate([("total", Sum::of(Book::price))]).
Ordering is ignored. A queryset with a limit, distinct or grouping is aggregated over its result rows.
§Errors
Capability (e.g. StdDev on SQLite) or backend errors.
Sourcepub fn subquery(self, field: impl Into<SelectExpr>) -> QueryPlan
pub fn subquery(self, field: impl Into<SelectExpr>) -> QueryPlan
This queryset as a subquery selecting only field, for
Field::in_subquery and Expr::subquery.
Sourcepub fn exists_expr(self) -> Expr
pub fn exists_expr(self) -> Expr
EXISTS (this queryset), for correlated filters:
Author::objects(&db).filter(Book::objects(&db).filter(..).exists_expr()).
Source§impl<M: Model> QuerySet<M>
impl<M: Model> QuerySet<M>
Sourcepub async fn update(
self,
assignments: impl IntoIterator<Item = (Ident, Expr)>,
) -> Result<u64, OrmError>
pub async fn update( self, assignments: impl IntoIterator<Item = (Ident, Expr)>, ) -> Result<u64, OrmError>
Set assignments (User::age.set(5), Post::likes.set_expr(Post::likes + 1))
on every matching row; returns the number of rows changed.
Runs one UPDATE. auto_now columns are not touched: name them in
assignments if they should change.
§Errors
Capability or backend errors (BackendError::Constraint for
violated constraints).
Sourcepub async fn delete(self) -> Result<u64, OrmError>
pub async fn delete(self) -> Result<u64, OrmError>
Delete every matching row; returns the number of rows removed.
Dependent rows follow the foreign keys’ database actions
(ON DELETE CASCADE / SET NULL / RESTRICT). A RESTRICT
(OnDelete::Protect) violation is reported as
BackendError::Constraint; nothing is deleted in that case.
§Errors
Capability or backend errors.
Sourcepub async fn create(self, object: M) -> Result<M, OrmError>
pub async fn create(self, object: M) -> Result<M, OrmError>
Insert object and return it as stored (generated key, database
defaults and stamped timestamps filled in).
§Errors
Capability or backend errors.
Sourcepub async fn get_or_create(
self,
predicate: Expr,
default: impl FnOnce() -> M + Send,
) -> Result<(M, bool), OrmError>
pub async fn get_or_create( self, predicate: Expr, default: impl FnOnce() -> M + Send, ) -> Result<(M, bool), OrmError>
The single row matching predicate, or a new one built by default
and inserted; the flag says whether it was created.
If a concurrent writer inserts the row first (unique violation), the
existing row is returned instead. When that re-fetch fails too, the
BackendError::Constraint is returned with the re-fetch error
appended to its message.
§Errors
QueryError::MultipleObjectsReturned, or capability / backend errors.
Sourcepub async fn update_or_create(
self,
predicate: Expr,
create: impl FnOnce() -> M + Send,
update: impl FnOnce(&mut M) + Send,
) -> Result<(M, bool), OrmError>
pub async fn update_or_create( self, predicate: Expr, create: impl FnOnce() -> M + Send, update: impl FnOnce(&mut M) + Send, ) -> Result<(M, bool), OrmError>
Apply update to the single row matching predicate and save it, or
insert the object built by create; the flag says whether it was
created. Runs in a transaction.
On backends with row locking the lookup is SELECT ... FOR UPDATE, so
concurrent updates of an existing row serialize instead of losing
writes. When the row is missing, two callers can both try to insert;
with a unique constraint covering predicate the loser’s insert fails
with BackendError::Constraint, and it retries once as lookup and
update in a new transaction. If that lookup misses too, the constraint
error is returned with the lookup’s error appended.
Backends without row locking (MongoDB) cannot lock the lookup, so two
concurrent updates of the same existing row can each read the old
values and the last save wins, losing the other’s changes. The ORM
has no conditional (versioned) save; where that matters, express the
change as an atomic update (e.g.
Post::likes.set_expr(Post::likes + 1)) instead. SQLite serializes
writers, so it is not affected.
§Errors
QueryError::MultipleObjectsReturned, or capability / backend errors.
Sourcepub async fn bulk_create(self, objects: Vec<M>) -> Result<Vec<M>, OrmError>
pub async fn bulk_create(self, objects: Vec<M>) -> Result<Vec<M>, OrmError>
Insert many objects with multi-row INSERTs, chunked to the backend’s
parameter limit, in one transaction. Returns the stored rows in input
order.
Requires RETURNING. Rows are matched back to the inputs by key, not
by the order the database returns them.
§Errors
Capability or backend errors; nothing is inserted on failure.
Sourcepub async fn bulk_update(
self,
objects: &[M],
columns: &[&'static str],
) -> Result<u64, OrmError>
pub async fn bulk_update( self, objects: &[M], columns: &[&'static str], ) -> Result<u64, OrmError>
Write columns of every object in objects back to its row, using
one UPDATE .. SET col = CASE pk WHEN .. END per chunk. Returns the
number of rows changed.
Values are written verbatim (auto_now is not refreshed). Objects
whose row is missing are skipped.
§Errors
QueryError::InvalidPlan for an unknown or primary-key column;
capability or backend errors.
Source§impl<M: Model> QuerySet<M>
impl<M: Model> QuerySet<M>
Sourcepub fn using(self, db: &Db) -> Self
pub fn using(self, db: &Db) -> Self
Run on db instead (Django using), e.g. a replica or the current
transaction handle.
Sourcepub fn with_plan(self, f: impl FnOnce(QueryPlan) -> QueryPlan) -> Self
pub fn with_plan(self, f: impl FnOnce(QueryPlan) -> QueryPlan) -> Self
Replace the plan (for extension code building on this queryset).
Sourcepub fn filter(self, predicate: Expr) -> Self
pub fn filter(self, predicate: Expr) -> Self
Keep rows matching predicate (ANDed with earlier filters).
A predicate over an aggregate annotation is applied as HAVING.
Sourcepub fn order_by(self, terms: impl IntoIterator<Item = OrderExpr>) -> Self
pub fn order_by(self, terms: impl IntoIterator<Item = OrderExpr>) -> Self
Replace the ordering (order_by([User::name.asc(), User::id.desc()])).
Sourcepub fn reverse(self) -> Self
pub fn reverse(self) -> Self
Flip every ordering direction. An unordered queryset is ordered by
primary key descending, so reverse().first() is the last row.
Sourcepub fn distinct_on<E: Into<Expr>>(
self,
exprs: impl IntoIterator<Item = E>,
) -> Self
pub fn distinct_on<E: Into<Expr>>( self, exprs: impl IntoIterator<Item = E>, ) -> Self
Keep the first row per distinct value of exprs (DISTINCT ON,
PostgreSQL only; combine with a matching order_by).
Sourcepub fn aliased(self, alias: impl Into<Ident>) -> Self
pub fn aliased(self, alias: impl Into<Ident>) -> Self
Name the root table in this query, so a subquery over the same table
can refer to the enclosing row with Expr::outer.
Sourcepub fn select_for_update(self) -> Self
pub fn select_for_update(self) -> Self
Lock the selected rows (SELECT .. FOR UPDATE). Backends without row
locking (SQLite) reject the query before running it. Locks are held
until the surrounding transaction ends, so use this inside
Db::transaction.
Sourcepub fn skip_locked(self) -> Self
pub fn skip_locked(self) -> Self
FOR UPDATE SKIP LOCKED: skip rows locked by other transactions.