Skip to main content

QuerySet

Struct QuerySet 

Source
pub struct QuerySet<M: Model> { /* private fields */ }
Expand description

Lazy query over model M.

Implementations§

Source§

impl<M: Model> QuerySet<M>

Source

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).

Source

pub fn union_all(self, other: QuerySet<M>) -> Result<Self, QueryError>

Rows in either queryset, keeping duplicates (UNION ALL).

§Errors

As union.

Source

pub fn intersection(self, other: QuerySet<M>) -> Result<Self, QueryError>

Rows in both querysets (INTERSECT).

§Errors

As union.

Source

pub fn difference(self, other: QuerySet<M>) -> Result<Self, QueryError>

Rows of this queryset that are not in other (EXCEPT).

§Errors

As union.

Source§

impl<M: Model> QuerySet<M>

Source

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.

Source

pub fn before(self, token: &str) -> Self

Page backwards from the position token names (a CursorPage::previous). See after.

Source

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>

Source

pub async fn all(self) -> Result<Vec<M>, OrmError>

Run the query and decode every row.

§Errors

Capability, backend or decode errors.

Source

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.

Source

pub async fn first(self) -> Result<Option<M>, OrmError>

The first row, if any. An unordered queryset is ordered by primary key.

§Errors

As all.

Source

pub async fn last(self) -> Result<Option<M>, OrmError>

The last row, if any: first on the reversed ordering.

§Errors

As all.

Source

pub async fn earliest(self, field: impl Into<Expr>) -> Result<M, OrmError>

The row with the smallest field.

§Errors

QueryError::DoesNotExist on an empty queryset, or as all.

Source

pub async fn latest(self, field: impl Into<Expr>) -> Result<M, OrmError>

The row with the largest field.

§Errors

QueryError::DoesNotExist on an empty queryset, or as all.

Source

pub async fn get(self, predicate: Expr) -> Result<M, OrmError>

Exactly one row matching predicate.

§Errors

QueryError::DoesNotExist, QueryError::MultipleObjectsReturned, or as all.

Source

pub async fn count(self) -> Result<u64, OrmError>

Number of matching rows.

§Errors

Capability or backend errors.

Source

pub async fn exists(self) -> Result<bool, OrmError>

Whether at least one row matches.

§Errors

Capability or backend errors.

Source

pub async fn contains(self, object: &M) -> Result<bool, OrmError>

Whether object is among the matching rows (by primary key).

§Errors

Capability or backend errors.

Source

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

pub async fn in_bulk( self, ids: impl IntoIterator<Item = M::Pk>, ) -> Result<HashMap<M::Pk, M>, OrmError>
where M::Pk: Eq + Hash,

Rows whose primary key is in ids, keyed by primary key (Django in_bulk). Missing keys are absent from the map.

§Errors

Capability or backend errors.

Source§

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>

Source

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.

Source

pub async fn rows(self) -> Result<Vec<Row>, OrmError>

Run the query and return its rows undecoded.

§Errors

Capability or backend errors.

Source

pub async fn values<S: Into<SelectExpr>>( self, fields: impl IntoIterator<Item = S>, ) -> Result<Vec<Row>, OrmError>

Rows holding only fields (Django values(..)).

§Errors

Capability or backend errors.

Source

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.

Source

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.

Source

pub fn subquery(self, field: impl Into<SelectExpr>) -> QueryPlan

This queryset as a subquery selecting only field, for Field::in_subquery and Expr::subquery.

Source

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>

Source

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).

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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>

Source

pub fn new(db: &Db) -> Self

Every row of M’s table, in the model’s default ordering.

Source

pub fn db(&self) -> &Db

The database handle this queryset runs on.

Source

pub fn plan(&self) -> &QueryPlan

The plan built so far.

Source

pub fn using(self, db: &Db) -> Self

Run on db instead (Django using), e.g. a replica or the current transaction handle.

Source

pub fn with_plan(self, f: impl FnOnce(QueryPlan) -> QueryPlan) -> Self

Replace the plan (for extension code building on this queryset).

Source

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.

Source

pub fn exclude(self, predicate: Expr) -> Self

Drop rows matching predicate.

Source

pub fn order_by(self, terms: impl IntoIterator<Item = OrderExpr>) -> Self

Replace the ordering (order_by([User::name.asc(), User::id.desc()])).

Source

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.

Source

pub fn limit(self, n: u64) -> Self

Return at most n rows.

Source

pub fn offset(self, n: u64) -> Self

Skip the first n rows.

Source

pub fn distinct(self) -> Self

Remove duplicate rows (SELECT DISTINCT).

Source

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).

Source

pub fn none(self) -> Self

A queryset that yields nothing and never queries the database.

Source

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.

Source

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.

Source

pub fn nowait(self) -> Self

FOR UPDATE NOWAIT: fail instead of waiting for locked rows.

Source

pub fn skip_locked(self) -> Self

FOR UPDATE SKIP LOCKED: skip rows locked by other transactions.

Source

pub fn annotate(self, name: impl Into<Ident>, expr: impl Into<Expr>) -> Self

Add expr to the result as column name (Django annotate).

Aggregates group by the other projected columns (see the module docs). Read the value with all_annotated or rows.

Source

pub fn alias(self, name: impl Into<Ident>, expr: impl Into<Expr>) -> Self

Name expr for use in filter / order_by without selecting it (Django alias).

Trait Implementations§

Source§

impl<M: Model> Clone for QuerySet<M>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<M: Model> Debug for QuerySet<M>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<M> !RefUnwindSafe for QuerySet<M>

§

impl<M> !UnwindSafe for QuerySet<M>

§

impl<M> Freeze for QuerySet<M>

§

impl<M> Send for QuerySet<M>

§

impl<M> Sync for QuerySet<M>

§

impl<M> Unpin for QuerySet<M>

§

impl<M> UnsafeUnpin for QuerySet<M>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more