← Back to Pull requests

[1b] Add typed where() with field-method conditions #84

Closed
unknown closed this pull request without merging on Sep 19, 2026 17:39 UTC
View on GitHub
unknown unknown commented on Jul 23, 2026 15:48 UTC
Author

What

A typed query API alongside filter():

User.query.where(
    User.email.equals("foo@example.com"),
    ~User.role.equals("admin"),
    User.age.gte(18),
)

Each argument is a Q built 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 Field

All of them, including the string-only ones:

  • Every field: equals, not_equal, gt, gte, lt, lte, is_null, is_in

  • String-valued fields: also contains, icontains, startswith, endswith
  • The string ones are on Field too, restricted by their self annotation:

    def contains(self: Field[str] | Field[str | None], value: str) -> Q: ...
    

    That restriction is doing real work. Since #83, models annotate fields with the base Field[T] — a field's declared type is Field[str], never TextField[str] — so anything living only on a subclass is invisible to the checker. Putting the methods on Field is what makes them reachable; the self type is what keeps Field[int].startswith(...) an error. It also means every string-valued field gets them regardless of base class: GenericIPAddressField is a DefaultableField and RandomStringField is a ColumnField, and neither inherits TextField.

    There is deliberately no runtime counterpart to that restriction. Contains, IContains, StartsWith and EndsWith are registered on Field itself (@Field.register_lookup in lookups.py), so IntegerField.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_q does reject a lookup a field hasn't registered at all.

    is_in refuses a bare str/bytes at runtime. Iterable[str] is satisfied by str, so name.is_in("abc") type-checks and would iterate characters; str is a Sequence[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_METHODS in fields/base.py next to the methods. Traversal and the tests import from there.

    Foreign-key traversal

    Accessing a field through a relation builds the joined lookup:

    Post.query.where(Post.author.email.equals("a@example.com"))  # Q(author__email="...")
    Post.query.where(Post.author.profile.city.equals("Topeka"))  # chains
    

    The mechanism is one method — Field.with_lookup_prefix(prefix) returns a detached copy of the field (via the existing Field.__copy__) whose name carries 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 full store__api_key path for free.

    Every relation encountered along the way is another hop, many-to-many included — WidgetTag.widget.tags.name.equals("metal") builds Q(widget__tags__name="metal"). One rule serves the first hop and every later one: the descriptor builds a RelatedFieldRef once (a cached_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: tags is declared ManyToManyManager[Tag], and claiming class access to an M2M yields type[Tag] would be false for Widget.tags itself, 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:

    Post.query.where(Post.author.id.equals(author.id))
    Post.query.where(Post.author.id.is_in([a.id for a in authors]))
    Post.query.where(Post.author.id.is_null())        # nullable relation
    

    This is the typed spelling of filter(author=author) and compiles to the same author__id= lookup — asserted directly in a test, not just claimed. Post.author.equals(author) raises an AttributeError naming this spelling (an AttributeError, not a TypeError, so hasattr and getattr(..., default) keep behaving).

    It can't be smoothed over: to the type checker Post.author is type[Author], which is precisely what makes Post.author.email.equals(...) type-check, and there is nowhere on type[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) returns self, 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 — and Meta skips _-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 named field or get_queryset silently resolved to the descriptor's attribute and built wrong SQL with no error.

    _get_prefetch_queryset is the duck-typed prefetch protocol, so the two manager classes and the single call site in query.py are renamed with it. Nothing outside plain-postgres references any of these; the managers keep their public get_queryset, and RelatedObjectDoesNotExist stays public on purpose (it is user-facing and documented).

    Returning the descriptor also means no inspect.getattr_static workarounds 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.

    RelatedFieldRef survives 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_q override on EncryptedField, refusing any suffix but isnull. 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 under if TYPE_CHECKING:. Narrowing an inherited parameter to Never is a Liskov violation — that is what makes it a compile-time block — so each carries # ty: ignore[invalid-method-override].

    EncryptedField[T] is the annotation

    api_key: EncryptedField[str] = types.EncryptedTextField(max_length=200)
    

    not Field[str]. The annotation is what the checker reads, and this is the Field[T] subclass that declares the blocks; a plain Field[str] hides them and lets Model.api_key.equals("x") type-check its way to a runtime TypeError. It types the synthesized constructor exactly as Field[T] does. Exported from plain.postgres alongside Field.

    Because a class-level suppression could otherwise hide a block that stopped blocking, test_every_blocked_method_is_rejected_statically pins the surface from outside: every blocked method gets a call site carrying # ty: ignore[invalid-argument-type] inside a pytest.raises(TypeError). ty reports an unused suppression as an error, so widening any parameter away from Never fails the type check — and the same statements assert the runtime raise, pinning both sides together. test_is_null_survives_the_block_statically carries no marker, so a Never creeping onto is_null() also breaks the build.

    Behavior change: get_or_create() on an encrypted field now raises

    get_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 into defaults=:

    Integration.query.get_or_create(name="acme", defaults={"api_key": "k"})
    

    Same for update_or_create() and for an expression right-hand side like filter(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 makes default="" expressible as a column DEFAULT). So filter(token=""), exclude(token="") and token.equals("") all keep working, and the typed path and the kwarg path allow exactly the same set. equals/not_equal are narrowed to those values statically rather than blocked outright; the other nine conditions stay Never.

    The kwarg path is blocked the same way: get_lookups() owns the complete registry and registers _EncryptedExact for "exact", which raises on a non-None right-hand value instead of silently returning zero rows, while None passes through so the exact-None → isnull rewrite still works. filter(api_key=None) still means IS NULL; filter(api_key="x") raises. It reads the field name from lhs.output_field.name and keeps its own sentence, because filter() 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 as ValueError("Cannot use None as a query value"), with no field in the message. It now raises a TypeError at the call site naming the field and the method. equals(None) (the ORM's exact-None rewrite) and is_null() stay legal.

    This one cannot be fixed statically. On a nullable field T includes None, and None can't be subtracted from a TypeVar. Probed against ty 0.0.80 and pyright 1.1.414: self: Field[X | None], value: X does* select the intended overload (confirmed by discriminating on distinct return types), but both solve X as int | None, so gte(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/ShadowSource to the examples test app, and the string-condition fixture adds StringConditionsExample (the repo's only GenericIPAddressField model, so it is what the end-to-end pattern tests run against). That moves the app's leaf migration, so tests/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 to examples is 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]: Any satisfies the model-valued __get__ overload, so class access types as type[Any] and the whole condition surface disappears without an error — use the concrete shape, or Field[object] when the column really does hold arbitrary JSON (plain-cache's value changes here for exactly that reason). And since class access now types as the related model, Model.fk.RelatedObjectDoesNotExist is a type error: catch Related.DoesNotExist (the exception subclasses it) or AttributeError.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: davegaeddert Review duration: 83630m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository