diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index 18741655d86..ab249e50a08 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -800,9 +800,8 @@ class SQLCompiler(object): # into `resolve_columns` because it wasn't selected. only_load = self.deferred_to_columns() if only_load: - db_table = self.query.model._meta.db_table - fields = [f for f in fields if db_table in only_load and - f.column in only_load[db_table]] + fields = [f for f in fields if f.model._meta.db_table not in only_load or + f.column in only_load[f.model._meta.db_table]] if has_aggregate_select: # pad None in to fields for aggregates fields = fields[:aggregate_start] + [ diff --git a/tests/regressiontests/queries/models.py b/tests/regressiontests/queries/models.py index 4ce696c277e..143e6206705 100644 --- a/tests/regressiontests/queries/models.py +++ b/tests/regressiontests/queries/models.py @@ -401,3 +401,12 @@ class ModelA(models.Model): name = models.TextField() b = models.ForeignKey(ModelB, null=True) d = models.ForeignKey(ModelD) + +class Ticket21203Parent(models.Model): + parentid = models.AutoField(primary_key=True) + parent_bool = models.BooleanField(default=True) + created = models.DateTimeField(auto_now=True) + +class Ticket21203Child(models.Model): + childid = models.AutoField(primary_key=True) + parent = models.ForeignKey(Ticket21203Parent) diff --git a/tests/regressiontests/queries/tests.py b/tests/regressiontests/queries/tests.py index 33e5337f581..c7e746e2d01 100644 --- a/tests/regressiontests/queries/tests.py +++ b/tests/regressiontests/queries/tests.py @@ -23,7 +23,8 @@ from .models import (Annotation, Article, Author, Celebrity, Child, Cover, Ranking, Related, Report, ReservedName, Tag, TvChef, Valid, X, Food, Eaten, Node, ObjectA, ObjectB, ObjectC, CategoryItem, SimpleCategory, SpecialCategory, OneToOneCategory, NullableName, ProxyCategory, - SingleObject, RelatedObject, ModelA, ModelD) + SingleObject, RelatedObject, ModelA, ModelD, + Ticket21203Parent, Ticket21203Child) class BaseQuerysetTest(TestCase): @@ -2149,3 +2150,11 @@ class EmptyStringPromotionTests(TestCase): self.assertIn('LEFT OUTER JOIN', str(qs.query)) else: self.assertNotIn('LEFT OUTER JOIN', str(qs.query)) + +class Ticket21203Tests(TestCase): + def test_ticket_21203(self): + p = Ticket21203Parent.objects.create(parent_bool=True) + c = Ticket21203Child.objects.create(parent=p) + qs = Ticket21203Child.objects.select_related('parent').defer('parent__created') + self.assertQuerysetEqual(qs, [c], lambda x: x) + self.assertIs(qs[0].parent.parent_bool, True)