summaryrefslogtreecommitdiff
path: root/django/forms
diff options
context:
space:
mode:
authorFrançois Freitag <mail@franek.fr>2018-04-13 18:15:22 -0700
committerTim Graham <timograham@gmail.com>2018-04-23 12:39:43 -0400
commit3fca95e1ad5b355f7813b98c97a194a30f2ab47b (patch)
treee8357bddc0c38b6035f2dbd03d67d45728ab7d82 /django/forms
parent9ec77f3d6633691c9bbf31d10af2313689170c85 (diff)
Fixed #28312 -- Made ModelChoiceIterator.__len__() more memory-efficient.
Instead of loading all QuerySet results in memory, count the number of entries. This adds an extra query when list() or tuple() is called on the choices (because both call __len__() then __iter__()) but uses less memory since the QuerySet results won't be cached. In most cases, the choices will only be iterated on, meaning that __len__() won't be called and only one query will be executed.
Diffstat (limited to 'django/forms')
-rw-r--r--django/forms/models.py7
1 files changed, 5 insertions, 2 deletions
diff --git a/django/forms/models.py b/django/forms/models.py
index d8db4b006a..67006ba390 100644
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -1134,13 +1134,16 @@ class ModelChoiceIterator:
yield ("", self.field.empty_label)
queryset = self.queryset
# Can't use iterator() when queryset uses prefetch_related()
- if not queryset._prefetch_related_lookups and queryset._result_cache is None:
+ if not queryset._prefetch_related_lookups:
queryset = queryset.iterator()
for obj in queryset:
yield self.choice(obj)
def __len__(self):
- return len(self.queryset) + (1 if self.field.empty_label is not None else 0)
+ # count() adds a query but uses less memory since the QuerySet results
+ # won't be cached. In most cases, the choices will only be iterated on,
+ # and __len__() won't be called.
+ return self.queryset.count() + (1 if self.field.empty_label is not None else 0)
def choice(self, obj):
return (self.field.prepare_value(obj), self.field.label_from_instance(obj))