Ticket #15494: only_pk.diff

File only_pk.diff, 2.2 KB (added by GDorn, 5 years ago)

Tests and better comments.

  • django/db/models/sql/query.py

     
    17381738        existing immediate values, but respects existing deferrals.)
    17391739        """
    17401740        existing, defer = self.deferred_loading
     1741        field_names = set(field_names)
     1742        if 'pk' in field_names:
     1743            field_names.remove('pk')
     1744            field_names.add(self.model._meta.pk.name)
     1745       
    17411746        if defer:
    17421747            # Remove any existing deferred names from the current set before
    17431748            # setting the new names.
    1744             self.deferred_loading = set(field_names).difference(existing), False
     1749            self.deferred_loading = field_names.difference(existing), False
    17451750        else:
    17461751            # Replace any existing "immediate load" field names.
    1747             self.deferred_loading = set(field_names), False
     1752            self.deferred_loading = field_names, False
    17481753
    17491754    def get_loaded_field_names(self):
    17501755        """
  • tests/modeltests/defer/tests.py

     
    2727        self.assert_delayed(qs.defer("name")[0], 1)
    2828        self.assert_delayed(qs.only("name")[0], 2)
    2929        self.assert_delayed(qs.defer("related__first")[0], 0)
     30       
     31        #Using 'pk' with only() should result in 3 deferred fields,
     32        #namely all of them except the model's primary key
     33        #see #15494
     34        self.assert_delayed(qs.only("pk")[0], 3)
    3035
    3136        obj = qs.select_related().only("related__first")[0]
    3237        self.assert_delayed(obj, 2)
    3338
    3439        self.assertEqual(obj.related_id, s1.pk)
     40       
     41        #You can use 'pk' with reverse foreign key lookups
     42        self.assert_delayed(s1.primary_set.all().only('pk')[0], 3)
    3543
    3644        self.assert_delayed(qs.defer("name").extra(select={"a": 1})[0], 1)
    3745        self.assert_delayed(qs.extra(select={"a": 1}).defer("name")[0], 1)
     
    135143        self.assertEqual(obj.other, "bar")
    136144        obj.name = "bb"
    137145        obj.save()
     146       
     147       
     148       
     149 No newline at end of file
Back to Top