Avoid doing quadratic amounts of work during object deletion.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@15243 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Alex Gaynor 2011-01-19 14:39:54 +00:00
parent 457aaca7fa
commit a38da1ae0d
1 changed files with 6 additions and 5 deletions

View File

@ -58,7 +58,8 @@ def force_managed(func):
class Collector(object): class Collector(object):
def __init__(self, using): def __init__(self, using):
self.using = using self.using = using
self.data = {} # {model: [instances]} # Initially, {model: set([instances])}, later values become lists.
self.data = {}
self.batches = {} # {model: {field: set([instances])}} self.batches = {} # {model: {field: set([instances])}}
self.field_updates = {} # {model: {(field, value): set([instances])}} self.field_updates = {} # {model: {(field, value): set([instances])}}
self.dependencies = {} # {model: set([models])} self.dependencies = {} # {model: set([models])}
@ -75,11 +76,11 @@ class Collector(object):
return [] return []
new_objs = [] new_objs = []
model = objs[0].__class__ model = objs[0].__class__
instances = self.data.setdefault(model, []) instances = self.data.setdefault(model, set())
for obj in objs: for obj in objs:
if obj not in instances: if obj not in instances:
new_objs.append(obj) new_objs.append(obj)
instances.extend(new_objs) instances.update(new_objs)
# Nullable relationships can be ignored -- they are nulled out before # Nullable relationships can be ignored -- they are nulled out before
# deleting, and therefore do not affect the order in which objects have # deleting, and therefore do not affect the order in which objects have
# to be deleted. # to be deleted.
@ -190,8 +191,8 @@ class Collector(object):
@force_managed @force_managed
def delete(self): def delete(self):
# sort instance collections # sort instance collections
for instances in self.data.itervalues(): for model, instances in self.data.items():
instances.sort(key=attrgetter("pk")) self.data[model] = sorted(instances, key=attrgetter("pk"))
# if possible, bring the models in an order suitable for databases that # if possible, bring the models in an order suitable for databases that
# don't support transactions or cannot defer contraint checks until the # don't support transactions or cannot defer contraint checks until the