diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 9a5666b143..27c6859c61 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -553,7 +553,10 @@ class Query(object): columns = set() orig_opts = self.model._meta seen = {} - must_include = {self.model: set([orig_opts.pk])} + if orig_opts.proxy: + must_include = {orig_opts.proxy_for_model: set([orig_opts.pk])} + else: + must_include = {self.model: set([orig_opts.pk])} for field_name in field_names: parts = field_name.split(LOOKUP_SEP) cur_model = self.model diff --git a/tests/regressiontests/defer_regress/models.py b/tests/regressiontests/defer_regress/models.py index 8db8c29960..4e4ab0a515 100644 --- a/tests/regressiontests/defer_regress/models.py +++ b/tests/regressiontests/defer_regress/models.py @@ -34,3 +34,7 @@ class Leaf(models.Model): class ResolveThis(models.Model): num = models.FloatField() name = models.CharField(max_length=16) + +class Proxy(Item): + class Meta: + proxy = True diff --git a/tests/regressiontests/defer_regress/tests.py b/tests/regressiontests/defer_regress/tests.py index 6f1b023b5b..fbcf85e078 100644 --- a/tests/regressiontests/defer_regress/tests.py +++ b/tests/regressiontests/defer_regress/tests.py @@ -7,7 +7,7 @@ from django.db import connection from django.db.models.loading import cache from django.test import TestCase -from models import ResolveThis, Item, RelatedItem, Child, Leaf +from models import ResolveThis, Item, RelatedItem, Child, Leaf, Proxy class DeferRegressionTest(TestCase): @@ -111,6 +111,7 @@ class DeferRegressionTest(TestCase): Child, Item, Leaf, + Proxy, RelatedItem, ResolveThis, ] @@ -139,6 +140,7 @@ class DeferRegressionTest(TestCase): "Leaf_Deferred_name_value", "Leaf_Deferred_second_child_value", "Leaf_Deferred_value", + "Proxy", "RelatedItem", "RelatedItem_Deferred_", "RelatedItem_Deferred_item_id", @@ -146,6 +148,21 @@ class DeferRegressionTest(TestCase): ] ) + def test_only_and_defer_usage_on_proxy_models(self): + # Regression for #15790 - only() broken for proxy models + proxy = Proxy.objects.create(name="proxy", value=42) + + msg = 'QuerySet.only() return bogus results with proxy models' + dp = Proxy.objects.only('other_value').get(pk=proxy.pk) + self.assertEqual(dp.name, proxy.name, msg=msg) + self.assertEqual(dp.value, proxy.value, msg=msg) + + # also test things with .defer() + msg = 'QuerySet.defer() return bogus results with proxy models' + dp = Proxy.objects.defer('name', 'text', 'value').get(pk=proxy.pk) + self.assertEqual(dp.name, proxy.name, msg=msg) + self.assertEqual(dp.value, proxy.value, msg=msg) + def test_resolve_columns(self): rt = ResolveThis.objects.create(num=5.0, name='Foobar') qs = ResolveThis.objects.defer('num')