1
0
mirror of https://github.com/django/django.git synced 2025-11-07 07:15:35 +00:00

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.
This commit is contained in:
François Freitag
2018-04-13 18:15:22 -07:00
committed by Tim Graham
parent 9ec77f3d66
commit 3fca95e1ad
3 changed files with 25 additions and 14 deletions

View File

@@ -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))