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

@ -2345,7 +2345,7 @@ class OtherModelFormTests(TestCase):
return ', '.join(c.name for c in obj.colours.all())
field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related('colours'))
with self.assertNumQueries(2): # would be 3 if prefetch is ignored
with self.assertNumQueries(3): # would be 4 if prefetch is ignored
self.assertEqual(tuple(field.choices), (
('', '---------'),
(multicolor_item.pk, 'blue, red'),