Queries
A query reads rows of a model’s table. It is rind’s QuerySet: you
build it with filter, exclude, order_by and the like, you pass it
around, you complete it, and then a Db runs it.
This chapter is the longest of the book, because queries are where most of an application’s logic lives. It is cut into sections, from the everyday to the advanced. Every example on these pages was run on the sample’s data, and the SQL shown is the SQL rind sent.
| Page | What it covers | In Django |
|---|---|---|
| A first query | one query from the code to the SQL; queries as values; typed paths; what differs from Django | |
| Running a query | db.all, first, count, rows; what comes back | evaluating a QuerySet, get(), first(), count() |
| Conditions | paths, comparisons, NULL, lists, & | ! | filter(field=…), field lookups, Q |
| Lookups on texts, arrays and JSON | case-insensitive searches, LIKE, arrays, JSON keys | iexact, icontains, ArrayField, JSONField lookups |
| Following relations | foreign keys, joins, many relations, EXISTS, exclude | origin__city=…, stops__station=…, exclude() |
| Ordering and pages | order_by, reorder, limit, offset | order_by(), slicing |
| Choosing the columns | select, tuples, all_partial, extra values | values_list(), only() |
| Expressions | arithmetic, SQL functions, constants, templates | F(), Func, Value, Coalesce |
| Aggregates | counts and sums per row, over a query, grouped | annotate(Count(…)), aggregate(), values().annotate() |
| Sub-queries | EXISTS, correlated values, IN (SELECT …) | Exists, Subquery, OuterRef |
| Loading related rows | the relations of a page, one query each | prefetch_related() |
| Writing rows | Insert, Update, Delete, links | create(), update(), delete(), add() |
| Trees | recursive walks: subtrees, ancestors, paths | django-mptt, django-treebeard |
| CTEs and unions | WITH, WITH RECURSIVE, UNION | union() |
| Transactions and locks | begin, commit, for_update | atomic(), select_for_update() |
| Raw SQL | when the query layer is not the right tool | raw(), cursor.execute() |
| Reference | every method, in tables |
The examples use the models of the railway and its seed
data (sample/seed.sql): six stations in five regions, three trains,
four journeys, five reservations. When a result is shown, it is what
that data gives.
Start with A first query: it holds the ideas the
other pages take for granted. If you look for the rind way of a Django
method, the Reference maps every
QuerySet method to its page.