Permalink
Browse files

Allow "pk" as a field alias in QuerySet.only() calls.

Thanks to GDorn for the patch. Fixed #15494.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16668 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
malcolmt committed Aug 23, 2011
1 parent a86dde2 commit 7182cd2284a15cd5094ab6567ae14c6ad3cd901a
Showing with 15 additions and 2 deletions.
  1. +7 −2 django/db/models/sql/query.py
  2. +8 −0 tests/modeltests/defer/tests.py
@@ -1791,13 +1791,18 @@ def add_immediate_loading(self, field_names):
existing immediate values, but respects existing deferrals.)
"""
existing, defer = self.deferred_loading
+ field_names = set(field_names)
+ if 'pk' in field_names:
+ field_names.remove('pk')
+ field_names.add(self.model._meta.pk.name)
+
if defer:
# Remove any existing deferred names from the current set before
# setting the new names.
- self.deferred_loading = set(field_names).difference(existing), False
+ self.deferred_loading = field_names.difference(existing), False
else:
# Replace any existing "immediate load" field names.
- self.deferred_loading = set(field_names), False
+ self.deferred_loading = field_names, False
def get_loaded_field_names(self):
"""
@@ -28,11 +28,18 @@ def test_defer(self):
self.assert_delayed(qs.only("name")[0], 2)
self.assert_delayed(qs.defer("related__first")[0], 0)
+ # Using 'pk' with only() should result in 3 deferred fields, namely all
+ # of them except the model's primary key see #15494
+ self.assert_delayed(qs.only("pk")[0], 3)
+
obj = qs.select_related().only("related__first")[0]
self.assert_delayed(obj, 2)
self.assertEqual(obj.related_id, s1.pk)
+ # You can use 'pk' with reverse foreign key lookups.
+ self.assert_delayed(s1.primary_set.all().only('pk')[0], 3)
+
self.assert_delayed(qs.defer("name").extra(select={"a": 1})[0], 1)
self.assert_delayed(qs.extra(select={"a": 1}).defer("name")[0], 1)
self.assert_delayed(qs.defer("name").defer("value")[0], 2)
@@ -135,3 +142,4 @@ def test_defer(self):
self.assertEqual(obj.other, "bar")
obj.name = "bb"
obj.save()
+

0 comments on commit 7182cd2

Please sign in to comment.