Django 6.1.3

8.2 From Python to SQL

Expressions, F, Value, and resolve_expression

What contract do F, Value, Func, When, and CombinedExpression share so Django can nest them arbitrarily inside filters, annotations, and updates?

Whether you write "F('priority') + 1", "Case(When(priority=1, then=Value('lead')), default=Value('inside'))", a SQL function like "Lower('headline')", or a correlated "Subquery", Django compiles them all through one uniform AST protocol defined in django/db/models/expressions.py. You can nest a Case inside a Func, add a Value to a Subquery, or pass any expression to QuerySet.filter, QuerySet.annotate, QuerySet.order_by, or QuerySet.update because every node obeys the exact same five-method contract on BaseExpression.

The BaseExpression contract and Combinable operators

Open django/db/models/expressions.py and trace the two mixins at the top of the hierarchy. Combinable implements Python’s arithmetic and bitwise dunder methods (__add__, __sub__, __mul__, __truediv__, __mod__, __pow__, plus their reflected "__r*__" twins). Whenever you evaluate "F('priority') + 1", Combinable._combine wraps the bare Python integer 1 in a Value and returns a CombinedExpression holding "lhs = F('priority')", "connector = '+'", and "rhs = Value(1)".

BaseExpression supplies the tree-walking and compilation lifecycle that every expression subclass — via Expression — inherits, using a Django Field to represent each node’s SQL result type:

Method or property Role in the compilation pipeline
get_source_expressions / set_source_expressions Exposes child expressions as a flat list so tree walkers can clone, relabel, and resolve recursively without knowing node internals.
resolve_expression Clones the node and recursively resolves every child against a concrete Query, turning symbolic F names into bound Col objects.
output_field Returns the Field instance describing the expression’s SQL result type — driving lookup dispatch, parameter preparation, and row converters.
as_sql (and as_<vendor>) Compiles the resolved node into a (sql, params) pair via SQLCompiler.compile.

Notice what happens during resolve_expression. On a composite node like CombinedExpression or Func, BaseExpression.resolve_expression shallow-copies "self", maps resolve_expression across "get_source_expressions()", and writes the resolved children back with "set_source_expressions()".

Turning F into Col and Value into "%s"

F is intentionally tiny: it is not a subclass of BaseExpression at all, only of Combinable. Until a Query gives it a model and an alias map, F("priority") is merely a symbolic name. When F.resolve_expression runs, it delegates straight to Query.resolve_ref.

Query.resolve_ref checks two places in order: first Query.annotations (so F("tier") can reference an earlier annotation alias, wrapping it in Ref, Ref, during aggregation), and otherwise it splits the string on "__", calls Query.setup_joins and Query.trim_joins, and returns a Col — or a Transform wrapping a Col if the path included transforms.

Once resolved, a Col holds an exact table alias ("newsroom_story") and a concrete Django Field ("newsroom.Story.priority"). Its Col.as_sql is five lines of code: quote the alias and column name through SQLCompiler.quote_name and return ('"newsroom_story"."priority"', ()). Meanwhile, Value.as_sql passes "self.value" through Field.get_db_prep_value (or Field.get_db_prep_save when "for_save=True" inside QuerySet.update) and returns ('%s', (val,)) — never interpolating the Python value into SQL, except for literal "NULL" when val is None.

Watch "F('priority') + 1" walk from raw CombinedExpression to resolved Col to compiled SQL on "desk/", alongside a Case / When expression and a deliberate type mismatch:

Recorded on Django 6.1.3 ch08-sql script
2. Expressions: F, Value, CombinedExpression, Col, and output_field
  raw_expr = <CombinedExpression: F(priority) + Value(1)> type=CombinedExpression lhs=F(priority) connector='+' rhs=Value(1)
  resolved_lhs = Col(newsroom_story, newsroom.Story.priority) type=Col output_field=IntegerField
  compiled_expr = sql='("newsroom_story"."priority" + %s)' params=(1,)
  case_sql = SELECT "newsroom_story"."slug" AS "slug", CASE WHEN "newsroom_story"."priority" = %s THEN %s ELSE %s END AS "tier" FROM "newsroom_story" ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
  case_params = (1, 'lead', 'inside')
  case_rows = [('bridge-bond-passes', 'lead'), ('city-budget-hearing', 'lead'), ('night-bus-schedule', 'lead'), ('water-main-repair', 'inside'), ('zoning-board-tables-plan', 'inside'), ('riverfront-stadium-lease', 'inside')]
  mixed_output_field_error = FieldError: Cannot infer type of '+' expression involving these types: PositiveSmallIntegerField, CharField. You must set output_field.

Why output_field exists — and when Django refuses to guess

Look at the two details in that recording that explain almost every cryptic FieldError developers hit with expressions.

First, look at "resolved_lhs" vs. "output_field": "Story.priority" is a PositiveSmallIntegerField, while Value(1) infers IntegerField inside Value._resolve_output_field. Because both are integer subclasses, output-field inference in BaseExpression._resolve_output_field reconciles them cleanly to IntegerField. The moment you add "F('priority') + F('headline')" — mixing PositiveSmallIntegerField and CharField — _resolve_output_field refuses to guess and raises FieldError, because without a single Field type, Django cannot know which lookups are legal on the result, how to adapt values for the backend, or which database converter to run on returned rows.

Second, look at Case and When. Every When(priority=1, then=Value('lead')) stores its condition as a Q object and resolves that condition through Query.build_filter during When.resolve_expression — which means any lookup or joined field legal inside QuerySet.filter works inside When, and every literal inside "then" and "default" still exits as a bound "%s" parameter (case_params = (1, 'lead', 'inside')).

The same BaseExpression contract also handles backend quirks via "as_<vendor>" overrides: Value.as_sqlite casts decimal.Decimal values to "REAL" or "NUMERIC" because SQLite has no fixed-precision decimal type, and CombinedExpression delegates operator syntax to BaseDatabaseOperations.combine_expression, which SQLite overrides to rewrite "^" into "POWER(...)".

Notice also that BaseExpression itself inherits from RegisterLookupMixin — wait: why does an expression know about lookups? Because in Django, a lookup does not just attach to a model Field; it attaches to the output field of any expression or transform in a double-underscore chain. We open that lookup registry next in Lookups, transforms, and the lookup registry.