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

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.

PageWhat it coversIn Django
A first queryone query from the code to the SQL; queries as values; typed paths; what differs from Django
Running a querydb.all, first, count, rows; what comes backevaluating a QuerySet, get(), first(), count()
Conditionspaths, comparisons, NULL, lists, & | !filter(field=…), field lookups, Q
Lookups on texts, arrays and JSONcase-insensitive searches, LIKE, arrays, JSON keysiexact, icontains, ArrayField, JSONField lookups
Following relationsforeign keys, joins, many relations, EXISTS, excludeorigin__city=…, stops__station=…, exclude()
Ordering and pagesorder_by, reorder, limit, offsetorder_by(), slicing
Choosing the columnsselect, tuples, all_partial, extra valuesvalues_list(), only()
Expressionsarithmetic, SQL functions, constants, templatesF(), Func, Value, Coalesce
Aggregatescounts and sums per row, over a query, groupedannotate(Count(…)), aggregate(), values().annotate()
Sub-queriesEXISTS, correlated values, IN (SELECT …)Exists, Subquery, OuterRef
Loading related rowsthe relations of a page, one query eachprefetch_related()
Writing rowsInsert, Update, Delete, linkscreate(), update(), delete(), add()
Treesrecursive walks: subtrees, ancestors, pathsdjango-mptt, django-treebeard
CTEs and unionsWITH, WITH RECURSIVE, UNIONunion()
Transactions and locksbegin, commit, for_updateatomic(), select_for_update()
Raw SQLwhen the query layer is not the right toolraw(), cursor.execute()
Referenceevery 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.