Ticket #21760: patch_21760_v2.diff

File patch_21760_v2.diff, 2.4 KB (added by valtron2000@…, 11 years ago)

Fixed patch

  • django/db/models/fields/related.py

    diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
    index 82e7725..46a81ff 100644
    a b class ReverseSingleRelatedObjectDescriptor(six.with_metaclass(RenameRelatedObjec  
    309309        rel_obj_attr = self.field.get_foreign_related_value
    310310        instance_attr = self.field.get_local_related_value
    311311        instances_dict = dict((instance_attr(inst), inst) for inst in instances)
    312         related_field = self.field.foreign_related_fields[0]
     312        related_fields = self.field.foreign_related_fields
    313313
    314314        # FIXME: This will need to be revisited when we introduce support for
    315315        # composite fields. In the meantime we take this practical approach to
    316316        # solve a regression on 1.6 when the reverse manager in hidden
    317317        # (related_name ends with a '+'). Refs #21410.
    318         if self.field.rel.is_hidden():
    319             query = {'%s__in' % related_field.name: set(instance_attr(inst)[0] for inst in instances)}
     318        if self.field.rel.is_hidden() or len(related_fields) == 1:
     319            query = {'%s__in' % related_fields[0].name: set(inst_attrs[0] for inst_attrs in instances_dict.keys())}
    320320        else:
    321321            query = {'%s__in' % self.field.related_query_name(): instances}
    322322
  • tests/prefetch_related/tests.py

    diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py
    index 5dfca0f..3bd6ec3 100644
    a b class Ticket21410Tests(TestCase):  
    996996
    997997    def test_bug(self):
    998998        list(Author2.objects.prefetch_related('first_book', 'favorite_books'))
     999
     1000
     1001class Ticket21760Tests(TestCase):
     1002
     1003    def setUp(self):
     1004        for _ in xrange(3):
     1005            house = House.objects.create()
     1006            for _ in xrange(3):
     1007                Room.objects.create(house = house)
     1008
     1009    @override_settings(DEBUG=True)
     1010    def test_bug(self):
     1011        with self.assertNumQueries(2):
     1012            rooms = list(Room.objects.all().prefetch_related('house'))
     1013
     1014        house_ids = {
     1015            r.house_id for r in rooms
     1016            if r.house_id
     1017        }
     1018
     1019        prefetch_query = connection.queries[-1]['sql']
     1020        lookup_id_str = prefetch_query.split('- PARAMS = ')[1]
     1021        lookup_ids = set(map(int, lookup_id_str[1:-1].split(', ')))
     1022
     1023        self.assertEqual(house_ids, lookup_ids)
Back to Top