Ticket #18556: t18556-remove-efficiency.diff

File t18556-remove-efficiency.diff, 2.5 KB (added by Alex, 3 years ago)
  • django/db/models/fields/related.py

    diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
    index 96d1438..9ddba43 100644
    a b class ForeignRelatedObjectsDescriptor(object): 
    523523            if rel_field.null:
    524524                def remove(self, *objs):
    525525                    val = getattr(self.instance, attname)
     526                    ids = []
    526527                    for obj in objs:
    527528                        # Is obj actually part of this descriptor set?
    528529                        if getattr(obj, rel_field.attname) == val:
    529                             setattr(obj, rel_field.name, None)
    530                             obj.save()
     530                            ids.append(obj.pk)
    531531                        else:
    532532                            raise rel_field.rel.to.DoesNotExist("%r is not related to %r." % (obj, self.instance))
     533                    self.filter(pk__in=ids).update(**{rel_field.name: None})
    533534                remove.alters_data = True
    534535
    535536                def clear(self):
  • django/db/models/related.py

    diff --git a/django/db/models/related.py b/django/db/models/related.py
    index 90995d7..08b825b 100644
    a b class RelatedObject(object): 
    3636                {'%s__isnull' % self.parent_model._meta.module_name: False})
    3737        lst = [(x._get_pk_val(), smart_unicode(x)) for x in queryset]
    3838        return first_choice + lst
    39        
     39
    4040    def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
    4141        # Defer to the actual field definition for db prep
    4242        return self.field.get_db_prep_lookup(lookup_type, value,
  • tests/modeltests/many_to_one_null/tests.py

    diff --git a/tests/modeltests/many_to_one_null/tests.py b/tests/modeltests/many_to_one_null/tests.py
    index 1a404bd..f367ea1 100644
    a b class ManyToOneNullTests(TestCase): 
    9292            r.article_set.create()
    9393        with self.assertNumQueries(1):
    9494            r.article_set.clear()
    95         self.assertEqual(r.article_set.count(), 0)
    96  No newline at end of file
     95        self.assertEqual(r.article_set.count(), 0)
     96
     97    def test_remove_efficiency(self):
     98        r = Reporter.objects.create()
     99        articles = []
     100        for _ in xrange(3):
     101            articles.append(r.article_set.create())
     102        with self.assertNumQueries(1):
     103            r.article_set.remove(*articles)
     104        self.assertEqual(r.article_set.count(), 0)
Back to Top