[1b] Add typed where() with field-method conditions #84
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #84"
general
weight: 0.35
davegaeddert
What
A typed query API alongside
filter():Each argument is a
Qbuilt from a real field, and positional conditions are ANDed. Because every condition comes from the field itself, a type checker rejects a misspelled field or a wrong value type at the call site — unlike string keyword lookups.QuerySet.where(conditions: Q)takes no kwargs at all, which is what makes that guarantee total.Conditions live on
FieldAll of them, including the string-only ones:
equals,not_equal,gt,gte,lt,lte,is_null,is_incontains,icontains,startswith,endswithThe string ones are on
Fieldtoo, restricted by theirselfannotation:That restriction is doing real work. Since #83, models annotate fields with the base
Field[T]— a field's declared type isField[str], neverTextField[str]— so anything living only on a subclass is invisible to the checker. Putting the methods onFieldis what makes them reachable; theselftype is what keepsField[int].startswith(...)an error. It also means every string-valued field gets them regardless of base class:GenericIPAddressFieldis aDefaultableFieldandRandomStringFieldis aColumnField, and neither inheritsTextField.There is deliberately no runtime counterpart to that restriction.
Contains,IContains,StartsWithandEndsWithare registered onFielditself (@Field.register_lookupinlookups.py), soIntegerField.get_lookup("contains")returns a real lookup and nothing at runtime tells a string field from an int one. The type level is the guard — the same type-first model the encrypted fields use — and the test says so rather than pretending otherwise._build_qdoes reject a lookup a field hasn't registered at all.is_inrefuses a barestr/bytesat runtime.Iterable[str]is satisfied bystr, soname.is_in("abc")type-checks and would iterate characters;stris aSequence[str], so excluding it statically isn't expressible either. The error names the list spelling.The method names are listed once, as
CONDITION_METHODS/STRING_CONDITION_METHODSinfields/base.pynext to the methods. Traversal and the tests import from there.Foreign-key traversal
Accessing a field through a relation builds the joined lookup:
The mechanism is one method —
Field.with_lookup_prefix(prefix)returns a detached copy of the field (via the existingField.__copy__) whosenamecarries the relation path. Traversal hands back the related model's own field, so its own condition methods build the right keys. Nothing re-implements or rewrites a field's surface, which means the traversed surface equals the direct surface by construction rather than by a gate that has to be kept in sync — including an encrypted field's refusals, whose message names the fullstore__api_keypath for free.Every relation encountered along the way is another hop, many-to-many included —
WidgetTag.widget.tags.name.equals("metal")buildsQ(widget__tags__name="metal"). One rule serves the first hop and every later one: the descriptor builds aRelatedFieldRefonce (acached_property, since the target may still be a string at construction) and delegates to it. That hop is runtime-only at the type level for now:tagsis declaredManyToManyManager[Tag], and claiming class access to an M2M yieldstype[Tag]would be false forWidget.tagsitself, which is not a traversal entry point.Conditions on the relation itself
A relation is not a field, so it carries no conditions. Match on the key it points at:
This is the typed spelling of
filter(author=author)and compiles to the sameauthor__id=lookup — asserted directly in a test, not just claimed.Post.author.equals(author)raises anAttributeErrornaming this spelling (anAttributeError, not aTypeError, sohasattrandgetattr(..., default)keep behaving).It can't be smoothed over: to the type checker
Post.authoristype[Author], which is precisely what makesPost.author.email.equals(...)type-check, and there is nowhere ontype[Author]to hang a condition method. A runtime method the checker rejects at every call site would be worse than none.Class-level FK access returns the descriptor
ForwardForeignKeyDescriptor.__get__(instance=None)returnsself, the ordinary descriptor convention. Traversal is served by__getattr__, which only fires for names the descriptor doesn't define.That works because the descriptor's own attributes are now
_-prefixed —_field,_is_cached,_get_queryset,_get_prefetch_queryset— andMetaskips_-prefixed attributes when it collects fields (meta.py), so a field name can never collide with a descriptor attribute. Shadowing is closed at the source rather than routed around: previously a related model with a column namedfieldorget_querysetsilently resolved to the descriptor's attribute and built wrong SQL with no error._get_prefetch_querysetis the duck-typed prefetch protocol, so the two manager classes and the single call site inquery.pyare renamed with it. Nothing outsideplain-postgresreferences any of these; the managers keep their publicget_queryset, andRelatedObjectDoesNotExiststays public on purpose (it is user-facing and documented).Returning the descriptor also means no
inspect.getattr_staticworkarounds in the prefetch path or__reduce__, no object allocated per class-level read, and no function-local import re-executed on every read: 39 ns per access, against 257 ns for the proxy this replaces.RelatedFieldRefsurvives for hops beyond the first, where there is a relation path to accumulate and no field to hand back yet.Encrypted fields: one runtime guard, eleven static declarations
Encrypted fields store non-deterministic ciphertext, so a value comparison can never match.
is_null()is the one condition that stays open — it reads the column's NULL-ness, not its contents.The runtime block is a single
_build_qoverride onEncryptedField, refusing any suffix butisnull. Every condition funnels through_build_q, so this covers conditions that don't exist yet, and the message names the method the caller actually wrote.The static block is eleven bodiless
Never-typed declarations underif TYPE_CHECKING:. Narrowing an inherited parameter toNeveris a Liskov violation — that is what makes it a compile-time block — so each carries# ty: ignore[invalid-method-override].EncryptedField[T]is the annotationnot
Field[str]. The annotation is what the checker reads, and this is theField[T]subclass that declares the blocks; a plainField[str]hides them and letsModel.api_key.equals("x")type-check its way to a runtimeTypeError. It types the synthesized constructor exactly asField[T]does. Exported fromplain.postgresalongsideField.Because a class-level suppression could otherwise hide a block that stopped blocking,
test_every_blocked_method_is_rejected_staticallypins the surface from outside: every blocked method gets a call site carrying# ty: ignore[invalid-argument-type]inside apytest.raises(TypeError). ty reports an unused suppression as an error, so widening any parameter away fromNeverfails the type check — and the same statements assert the runtime raise, pinning both sides together.test_is_null_survives_the_block_staticallycarries no marker, so aNevercreeping ontois_null()also breaks the build.Behavior change:
get_or_create()on an encrypted field now raisesget_or_create(api_key="k")used to "work" — and quietly created a new row on every call, because the lookup could never match existing ciphertext. It now raises, and the message says to move the value intodefaults=:Same for
update_or_create()and for an expression right-hand side likefilter(api_key=F("name")). This is the deliberate half of the block: silent duplication is what it exists to prevent. An encrypted value can be written, just not looked up.What still matches:
None, and — on a string-valued encrypted field — the empty string, which is stored as plaintext''(that is what makesdefault=""expressible as a column DEFAULT). Sofilter(token=""),exclude(token="")andtoken.equals("")all keep working, and the typed path and the kwarg path allow exactly the same set.equals/not_equalare narrowed to those values statically rather than blocked outright; the other nine conditions stayNever.The kwarg path is blocked the same way:
get_lookups()owns the complete registry and registers_EncryptedExactfor"exact", which raises on a non-Noneright-hand value instead of silently returning zero rows, whileNonepasses through so theexact-None→isnullrewrite still works.filter(api_key=None)still meansIS NULL;filter(api_key="x")raises. It reads the field name fromlhs.output_field.nameand keeps its own sentence, becausefilter()is supported here — just not against a value.None operands on ordering conditions
age.gte(None)used to get past the checker and die much later asValueError("Cannot use None as a query value"), with no field in the message. It now raises aTypeErrorat the call site naming the field and the method.equals(None)(the ORM's exact-Nonerewrite) andis_null()stay legal.This one cannot be fixed statically. On a nullable field
TincludesNone, andNonecan't be subtracted from a TypeVar. Probed against ty 0.0.80 and pyright 1.1.414:self: Field[X | None], value: Xdoes* select the intended overload (confirmed by discriminating on distinct return types), but both solveXasint | None, sogte(None)type-checks either way. A constrained TypeVar doesn't help. The runtime refusal is the guard, and the test records why there is no static pin next to it.Also in this branch
The shadowing fixtures add
ShadowTarget/ShadowSourceto theexamplestest app, and the string-condition fixture addsStringConditionsExample(the repo's onlyGenericIPAddressFieldmodel, so it is what the end-to-end pattern tests run against). That moves the app's leaf migration, sotests/internal/test_migrations_reset.py— which had pinned the leaf, baseline name, migration numbers and file counts by hand — now derives all of them from the real history, including the models the leaf creates. Any future branch that adds a migration toexamplesis unaffected.That part is independent of
where().Tests / checks
./scripts/fix— clean./scripts/type-check .— clean, whole repo (ty 0.0.80). The# ty: ignore[...]markers in the typed-where and encrypted-field tests are load-bearing regression detectors, not noise. The overload choices above were cross-checked against pyright 1.1.414 as well../scripts/test— all 27 package suites plus the example project green: 2613 passed, 1 skipped.plain-postgres: 983 passed, 1 skipped.plain: 697 passed.Diff against master: 24 files, +1826 / −113.
Two annotation notes that outlive this PR. Never annotate a field
Field[Any]:Anysatisfies the model-valued__get__overload, so class access types astype[Any]and the whole condition surface disappears without an error — use the concrete shape, orField[object]when the column really does hold arbitrary JSON (plain-cache'svaluechanges here for exactly that reason). And since class access now types as the related model,Model.fk.RelatedObjectDoesNotExistis a type error: catchRelated.DoesNotExist(the exception subclasses it) orAttributeError.