From 87c63bd8df0eb0109df333df1264c6a96707d6a4 Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Tue, 4 Apr 2023 16:58:15 -0400 Subject: [PATCH] Fixed #34458 -- Fixed QuerySet.defer() crash on attribute names. Thanks Andrew Cordery for the report. Regression in b3db6c8dcb5145f7d45eff517bcd96460475c879. --- django/db/models/sql/query.py | 3 ++- docs/releases/4.2.1.txt | 3 ++- tests/defer/tests.py | 5 +++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 4f09f73de3d..ef55dbe3a94 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -702,7 +702,8 @@ class Query(BaseExpression): # by recursively calling this function. for field in opts.concrete_fields: field_mask = mask.pop(field.name, None) - if field_mask is None: + field_att_mask = mask.pop(field.attname, None) + if field_mask is None and field_att_mask is None: select_mask.setdefault(field, {}) elif field_mask: if not field.is_relation: diff --git a/docs/releases/4.2.1.txt b/docs/releases/4.2.1.txt index fb3edf50bce..2dd051b8fa1 100644 --- a/docs/releases/4.2.1.txt +++ b/docs/releases/4.2.1.txt @@ -9,4 +9,5 @@ Django 4.2.1 fixes several bugs in 4.2. Bugfixes ======== -* ... +* Fixed a regression in Django 4.2 that caused a crash of ``QuerySet.defer()`` + when deferring fields by attribute names (:ticket:`34458`). diff --git a/tests/defer/tests.py b/tests/defer/tests.py index 34544b4bef0..c7eb03dc8af 100644 --- a/tests/defer/tests.py +++ b/tests/defer/tests.py @@ -178,6 +178,11 @@ class DeferTests(AssertionMixin, TestCase): obj = ShadowChild.objects.defer("name").get() self.assertEqual(obj.name, "adonis") + def test_defer_fk_attname(self): + primary = Primary.objects.defer("related_id").get() + with self.assertNumQueries(1): + self.assertEqual(primary.related_id, self.p1.related_id) + class BigChildDeferTests(AssertionMixin, TestCase): @classmethod