Every method of the query layer, in tables. The other pages of this
chapter explain them with examples; the links lead there.
Every QuerySet method a Django developer reaches for, and where it is
in rind. Each line links to the page that explains it.
| Django | rind | Page |
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, !a | Conditions |
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 paths | Relations |
.distinct() after a filter on a many relation | not needed: the filter is an EXISTS | Relations |
.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.rows | Selecting |
.only("id", "name") | db.all_partial(&q, &["id", "name"]) | Selecting |
F("platforms") + 1 | Station::platforms() + 1 | Expressions |
Coalesce(…), Now(), Func(…) | func::coalesce, func::now, func::call | Expressions |
.annotate(n=Count("wagons")) | Train::wagons().count() in a select, a filter or an order | Aggregates |
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 |
| Method | SQL | Django | Page |
eq(v), ne(v) | =, <> | exact, exclude(…) | Conditions |
lt, le, gt, ge | <, <=, >, >= | lt, lte, gt, gte | Conditions |
distinct_from(v), not_distinct_from(v) | IS DISTINCT FROM, IS NOT DISTINCT FROM | | Conditions |
in_(values) | IN (…); = ANY($1) beyond 1,000 values; FALSE for an empty list | in | Conditions |
in_sub(select) | IN (SELECT …) | in with a queryset | Sub-queries |
is_null(), is_not_null() | IS NULL, IS NOT NULL | isnull | Conditions |
like(p), ilike(p) | LIKE, ILIKE | | Lookups |
iexact(t) | upper(a) = upper(t) | iexact | Lookups |
icontains(t), istartswith(t) | upper(a) LIKE upper('%t%'), … 't%' | icontains, istartswith | Lookups |
contains(values) on an array | @> | ArrayField’s contains | Lookups |
overlaps(values) on an array | && | overlap | Lookups |
has_key(k), has_any_key(ks) on JSON | ?, ?| | has_key, has_any_keys | Lookups |
rel.any(|r| cond) on a many relation | EXISTS (…) | rel__… | Relations |
| geographic conditions | | GeoDjango | Geography |
Conditions combine with &, | and !; Cond::Const(true) and
Cond::Const(false) always and never match.
| On | Method | Gives |
| 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 |
| Over | Methods | Page |
| a many relation, per row | rel().count(); rel().rows() or rel().filter(|r| …), then .count(), .sum(|r| …), .avg, .min, .max, .std_dev, .std_dev_sample; .grouped() | Aggregates |
| the whole query | func::count(), func::sum(x), func::avg, func::min, func::max, func::std_dev | Aggregates |
| groups | group_by(keys), having(cond), with func::… and .array_agg() | Aggregates |
| Aggregate | Read as | With no rows |
| count | i64 | 0 |
| sum | Option<i64> (integers), Option<f64> (floats) | None |
| avg, std_dev, std_dev_sample | Option<f64> | None |
| min, max | Option<T>, T the column’s SQL type | None |
| Method | What 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 |
| Method | Answers | Page |
all(&query) | Vec<M> | Running |
all_partial(&query, &columns) | Vec<M>, only these columns filled | Selecting |
first(&query) | Option<M>, with LIMIT 1 and no added order | Running |
count(&query) | i64, without order or page | Running |
rows(&select) | Vec<R>, R a tuple of up to six, or any FromRow | Selecting |
insert(&insert) | M, as stored | Writing |
insert_keyed(&insert) | (i64, M): the new key, and the row | Writing |
execute(&update) | u64, rows changed | Writing |
delete(&delete) | u64, rows deleted | Writing |
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, removed | Writing |
begin() | Tx: tx.db(), tx.commit(), tx.rollback() | Transactions |
in_transaction() | bool | Transactions |
query_sql(sql, ¶ms) | Vec<R> | Raw SQL |
execute_sql(sql, ¶ms) | u64 | Raw SQL |
batch_execute(sql) | (): several statements, no parameters | Raw SQL |
| Builder | Methods |
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 |
| Function | What 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 |
| Function | What 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 |
These Django features have no equivalent yet. Write them in
raw SQL when you need them:
| Django | Note |
Case(When(…)) | conditional values |
Window, RowNumber, Rank, Lag | window functions |
bulk_create, bulk_update | one statement for many rows: loop in a transaction |
get_or_create, update_or_create | INSERT … 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) |
__regex | a template |
TimeField, DurationField, UUIDField columns | Fields |