Skip to content

fix: KeyError when accessing fields deferred by base manager#907

Merged
bckohan merged 2 commits into
django-commons:mainfrom
chrisimcevoy:deferred-field-access-keyerror
Jul 9, 2026
Merged

fix: KeyError when accessing fields deferred by base manager#907
bckohan merged 2 commits into
django-commons:mainfrom
chrisimcevoy:deferred-field-access-keyerror

Conversation

@chrisimcevoy

Copy link
Copy Markdown
Contributor

Ensure that injecting "polymorphic_ctype_id" into deferred_loading happens after Django's .only() implementation has determined which deferred fields to read.

closes #906

@chrisimcevoy chrisimcevoy requested a review from bckohan as a code owner July 9, 2026 12:46
Copilot AI review requested due to automatic review settings July 9, 2026 12:46
Comment thread src/polymorphic/tests/test_orm.py

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes a regression where accessing model fields that are deferred by a polymorphic model’s base manager can raise KeyError, by ensuring polymorphic_ctype_id is added to Django’s deferred-loading configuration after Django’s .only() logic has determined immediate vs deferred fields.

Changes:

  • Adjust PolymorphicQuerySet.only() to inject polymorphic_ctype_id by post-processing clone.query.deferred_loading, avoiding interference with Django’s deferred-field set-difference logic.
  • Add a regression test case and supporting test model/DB migration to reproduce “base manager defers a field” behavior.
  • Update justfile setting syntax (set unstable).

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/polymorphic/query.py Changes .only() handling so polymorphic_ctype_id is included without breaking Django’s deferred-field tracking.
src/polymorphic/tests/test_orm.py Adds regression test that exercises deferred field access through a base manager that uses .defer().
src/polymorphic/tests/models.py Introduces a test-only manager and model variant to defer a field via the base manager.
src/polymorphic/tests/migrations/0001_initial.py Adds migration for the new test model so the test DB schema matches.
src/polymorphic/tests/test_utils.py Updates concrete descendant expectations to include the new test model.
justfile Updates just setting syntax for unstable.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@bckohan bckohan force-pushed the deferred-field-access-keyerror branch from a291045 to e5cd637 Compare July 9, 2026 16:35

@bckohan bckohan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a solid, correct fix. I traced the mechanics and verified it end-to-end.

Root cause. Django stores field-loading intent as query.deferred_loading = (field_set, defer_flag):

  • (fields, True) → defer these (load everything else)
  • (fields, False) → load only these
  • (∅, False) → the empty-only special case, which Django's deferred_to_data treats as load all fields

The scenario: a model whose base_manager defers field2 (DeferredManager.get_queryset().defer("field2")). When you later access obj.field2, Django's DeferredAttribute.get calls refresh_from_db(fields=["field2"]), which runs ._base_manager.only("field2").get(). That base-manager queryset already carries deferred_loading = ({"field2"}, True). Django's add_immediate_loading then computes {"field2"} - {"field2"} = ∅, flipping to (∅, False) — i.e. "load everything."

The old only() unconditionally injected polymorphic_ctype_id before calling super().only(), so the result became ({"polymorphic_ctype_id"}, False) — "load only ctype." field2 stayed deferred, the refresh never fetched it, and re-reading data["field2"] blew up with KeyError: 'field2'.

The fix moves the injection to after super().only() and gates it on the resulting only-set being non-empty. In the collapse-to-load-all case it leaves (∅, False) alone (all fields load, including ctype); in the normal .only("field1") case it re-adds ctype exactly as before.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
src/polymorphic/__init__.py 100.00% <100.00%> (ø)
src/polymorphic/query.py 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bckohan bckohan merged commit 69d68b5 into django-commons:main Jul 9, 2026
53 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fields deferred by base manager raise KeyError when accessed.

4 participants