Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Reference

Every method of the query layer, in tables. The other pages of this chapter explain them with examples; the links lead there.

Django’s QuerySet, in rind

Every QuerySet method a Django developer reaches for, and where it is in rind. Each line links to the page that explains it.

DjangorindPage
Station.objects.all()Query::<Station>::new()Running
list(qs), qs.first(), qs.count()db.all(&q), db.first(&q), db.count(&q)Running
.filter(status="open", platforms__gte=4).filter(Station::status().eq("open") & Station::platforms().ge(4))Conditions
Q(a) | Q(b), ~Q(a)a | b, !aConditions
field__isnull=True.is_null()Conditions
field__in=[…].in_([…])Conditions
name__icontains="x"Station::name().icontains("x")Lookups
services__contains=[…]Station::services().contains([…])Lookups
.filter(origin__city="Paris").filter(Journey::origin().city().eq("Paris"))Relations
.filter(stops__station=2).filter(Journey::stops().any(|s| s.station_id().eq(2)))Relations
.exclude(…).exclude(…)Relations
select_related("origin")nothing to write: the joins follow the pathsRelations
.distinct() after a filter on a many relationnot needed: the filter is an EXISTSRelations
.order_by("-name"), qs[40:60].order_by([Station::name().desc()]), .offset(40).limit(20)Ordering
.values_list("code", "origin__city").select((Journey::code(), Journey::origin().city())) and db.rowsSelecting
.only("id", "name")db.all_partial(&q, &["id", "name"])Selecting
F("platforms") + 1Station::platforms() + 1Expressions
Coalesce(…), Now(), Func(…)func::coalesce, func::now, func::callExpressions
.annotate(n=Count("wagons"))Train::wagons().count() in a select, a filter or an orderAggregates
Count("wagons", filter=Q(…))Train::wagons().filter(|w| …).count()Aggregates
.aggregate(Sum("capacity")).select(func::sum(Wagon::capacity()))Aggregates
.values("journey").annotate(n=Count("id")).group_by(Reservation::journey_id()).select((…, func::count()))Aggregates
Exists(…), OuterRef("pk")query.exists(), Station::id().outer()Sub-queries
Subquery(qs.values("x")[:1])query.limit(1).scalar(…)Sub-queries
prefetch_related("wagons")db.load_many(…), db.load_one(…), db.load_m2m(…)Loading
Model.objects.create(…)db.insert(&Insert::<M>::new().value(…))Writing
.update(status="retired")db.execute(&Update::<M>::new().set(…).filter(…))Writing
.delete()db.delete(&Delete::<M>::new().filter(…))Writing
user.groups.add(g), .remove(g)db.link(&USER_GROUPS, user, g), db.unlink(…)Writing
django-mptt’s get_descendants()Region::subtree(id)Trees
.union(…).union(…), .union_all(…)CTEs and unions
transaction.atomic()db.begin() … tx.commit()Transactions
.select_for_update().for_update()Transactions
Model.objects.raw(…), cursor.execute(…)db.query_sql(…), db.execute_sql(…)Raw SQL

Conditions on a path

MethodSQLDjangoPage
eq(v), ne(v)=, <>exact, exclude(…)Conditions
lt, le, gt, ge<, <=, >, >=lt, lte, gt, gteConditions
distinct_from(v), not_distinct_from(v)IS DISTINCT FROM, IS NOT DISTINCT FROMConditions
in_(values)IN (…); = ANY($1) beyond 1,000 values; FALSE for an empty listinConditions
in_sub(select)IN (SELECT …)in with a querysetSub-queries
is_null(), is_not_null()IS NULL, IS NOT NULLisnullConditions
like(p), ilike(p)LIKE, ILIKELookups
iexact(t)upper(a) = upper(t)iexactLookups
icontains(t), istartswith(t)upper(a) LIKE upper('%t%'), … 't%'icontains, istartswithLookups
contains(values) on an array@>ArrayField’s containsLookups
overlaps(values) on an array&&overlapLookups
has_key(k), has_any_key(ks) on JSON?, ?|has_key, has_any_keysLookups
rel.any(|r| cond) on a many relationEXISTS (…)rel__…Relations
geographic conditionsGeoDjangoGeography

Conditions combine with &, | and !; Cond::Const(true) and Cond::Const(false) always and never match.

Expressions

OnMethodGives
a path.expr()the path as an expression
a path.outer()the column of the enclosing query (Sub-queries)
a path or expression.asc(), .desc()an order item
a path or expression.as_("name")a named selected value
an expression.wrap::<U>("…{}…")an SQL template (Expressions)
a number+, -, *, /, unary -arithmetic
a text.upper(), .unaccent()upper(…), unaccent(…)
a text array.as_text()CAST(… AS text)
JSON.json_text(k)->> 'k'
an integer path.array_agg()ARRAY_AGG(… ORDER BY …) in a grouped query
—func::coalesce(a, b), func::now(), func::int(n), func::text(s), func::call::<T, A>(name, arg)SQL functions and constants

Aggregates

OverMethodsPage
a many relation, per rowrel().count(); rel().rows() or rel().filter(|r| …), then .count(), .sum(|r| …), .avg, .min, .max, .std_dev, .std_dev_sample; .grouped()Aggregates
the whole queryfunc::count(), func::sum(x), func::avg, func::min, func::max, func::std_devAggregates
groupsgroup_by(keys), having(cond), with func::… and .array_agg()Aggregates
AggregateRead asWith no rows
counti640
sumOption<i64> (integers), Option<f64> (floats)None
avg, std_dev, std_dev_sampleOption<f64>None
min, maxOption<T>, T the column’s SQL typeNone

Methods of Query<M>

MethodWhat it does
Query::new()every row; not for a scoped model
Query::all()every row, said explicitly: also for a scoped model
filter(cond)keeps the rows that match; successive calls combine with AND
exclude(cond)keeps the rows where cond is false or unknown (Relations)
order_by(items), reorder(items)adds to the order; replaces it (Ordering)
limit(n), offset(n)the page
select(columns)what is read: a path, an expression, or a tuple of up to six (Selecting)
extra(name, value), Query::extra_value(name)a value beside the model’s columns, and a reference to it
group_by(keys), having(cond)a grouped query
union(q), union_all(q)the rows of both queries (Unions)
with(&cte), join_cte(&cte.r(), on)a CTE, and a join to it (CTEs)
with_tree(&tree)a tree walk, joined (Trees)
for_update()locks the rows read (Transactions)
exists()the query as a condition (Sub-queries)
scalar(value), scalar_count()the query as a value
into_select(), as_select()the untyped Select, for db.rows
count()the Select of COUNT(*), without order or page; for a grouped query, of the groups
only(&columns)the Select of some columns only (what all_partial sends)
to_sql()the SQL and its parameters, without running it

Methods of Db

MethodAnswersPage
all(&query)Vec<M>Running
all_partial(&query, &columns)Vec<M>, only these columns filledSelecting
first(&query)Option<M>, with LIMIT 1 and no added orderRunning
count(&query)i64, without order or pageRunning
rows(&select)Vec<R>, R a tuple of up to six, or any FromRowSelecting
insert(&insert)M, as storedWriting
insert_keyed(&insert)(i64, M): the new key, and the rowWriting
execute(&update)u64, rows changedWriting
delete(&delete)u64, rows deletedWriting
load_one(query, keys)HashMap<i64, M>Loading
load_many(query, key, keys)HashMap<i64, Vec<M>>Loading
load_m2m(query, &hop, keys)HashMap<i64, Vec<M>>Loading
load_m2m_ids(&hop, keys, link_order), load_m2m_ids_in(query, &hop, keys)HashMap<i64, Vec<i64>>Loading
link(&hop, from, to), unlink(&hop, from, to)bool: whether a link was added, removedWriting
begin()Tx: tx.db(), tx.commit(), tx.rollback()Transactions
in_transaction()boolTransactions
query_sql(sql, &params)Vec<R>Raw SQL
execute_sql(sql, &params)u64Raw SQL
batch_execute(sql)(): several statements, no parametersRaw SQL

Statements

BuilderMethods
Insert::<M>::new()value(path, v), to_sql()
Update::<M>::new()set(path, v), filter(cond), to_sql(); refused without a filter
Delete::<M>::new()filter(cond), to_sql(); refused without a filter

CTEs

FunctionWhat it is
Cte::new(name, &columns, query)WITH name(columns) AS (query)
Cte::recursive(name, &columns, base, |cte| step)WITH RECURSIVE … (base UNION ALL step)
cte.r()a reference, to join: join_cte(&cte.r(), on)
cte.col::<T>("c")a column, as an expression
cte.select("c")SELECT c FROM cte, for in_sub

Tree functions of a model

FunctionWhat it is
subtree(start), subtree_where(cond)keys for in_sub: the rows and below; options without_self, include_self(bool), max_down, down_to_level, at_level, stop_at, with_start
ancestry(start), ancestry_where(cond)keys for in_sub: the rows and above; options without_self, include_self(bool), max_up, up_to_level, at_level, with_start
paths(&db, ids, column)for each row, its ancestors from the root, with a column of each
tree(order), tree_by_text(order)every row with depth(), path(), key(); ordered by asc(), desc()
descendants(id), descendants_of(ids), ancestors_of(ids)the walks as CTEs, with a start column

Not available

These Django features have no equivalent yet. Write them in raw SQL when you need them:

DjangoNote
Case(When(…))conditional values
Window, RowNumber, Rank, Lagwindow functions
bulk_create, bulk_updateone statement for many rows: loop in a transaction
get_or_create, update_or_createINSERT … ON CONFLICT
select_for_update(nowait=True, skip_locked=True)
nested atomic()savepoints
__year, __month, __date…a range of moments, or a template
contains, startswith, endswith (case-sensitive)like with like_escape (Lookups)
__regexa template
TimeField, DurationField, UUIDField columnsFields