Permalink
Browse files

Made clear() on a reverse foreign key significantly more efficient. T…

…hanks to Andrew Godwin for the review.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16335 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
1 parent 684b039 commit fcf8312ade4375faf6027afe610fb76bcdead084 @alex alex committed Jun 7, 2011
@@ -459,9 +459,7 @@ def remove(self, *objs):
remove.alters_data = True
def clear(self):
- for obj in self.all():
- setattr(obj, rel_field.name, None)
- obj.save()
+ self.update(**{rel_field.name: None})
clear.alters_data = True
manager = RelatedManager()
@@ -1,10 +1,13 @@
+from copy import deepcopy
from datetime import datetime
+
from django.test import TestCase
from django.core.exceptions import FieldError
+
from models import Article, Reporter
-class ManyToOneTests(TestCase):
+class ManyToOneTests(TestCase):
def setUp(self):
# Create a few Reporters.
self.r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
@@ -368,5 +371,4 @@ def test_regression_12876(self):
# Regression for #12876 -- Model methods that include queries that
# recursive don't cause recursion depth problems under deepcopy.
self.r.cached_query = Article.objects.filter(reporter=self.r)
- from copy import deepcopy
self.assertEqual(repr(deepcopy(self.r)), "<Reporter: John Smith>")
@@ -1,8 +1,10 @@
+from __future__ import with_statement
+
from django.test import TestCase
from models import Reporter, Article
-class ManyToOneNullTests(TestCase):
+class ManyToOneNullTests(TestCase):
def setUp(self):
# Create a Reporter.
self.r = Reporter(name='John Smith')
@@ -82,3 +84,11 @@ def test_assign_clear_related_set(self):
self.assertQuerysetEqual(self.r.article_set.all(), [])
self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True),
['<Article: First>', '<Article: Fourth>'])
+
+ def test_remove_efficiency(self):
+ r = Reporter.objects.create()
+ for _ in xrange(3):
+ r.article_set.create()
+ with self.assertNumQueries(1):
+ r.article_set.clear()
+ self.assertEqual(r.article_set.count(), 0)

0 comments on commit fcf8312

Please sign in to comment.