1
0
mirror of https://github.com/django/django.git synced 2024-12-23 01:25:58 +00:00

Refs #28312 -- Added an optimized __bool__() to ModelChoiceIterator.

COUNT is more expensive than EXISTS; use the latter when possible.
This commit is contained in:
François Freitag 2018-04-13 18:39:10 -07:00 committed by Tim Graham
parent 3fca95e1ad
commit d1413c5d70
2 changed files with 14 additions and 0 deletions

View File

@ -1145,6 +1145,9 @@ class ModelChoiceIterator:
# and __len__() won't be called.
return self.queryset.count() + (1 if self.field.empty_label is not None else 0)
def __bool__(self):
return self.field.empty_label is not None or self.queryset.exists()
def choice(self, obj):
return (self.field.prepare_value(obj), self.field.label_from_instance(obj))

View File

@ -115,6 +115,17 @@ class ModelChoiceFieldTests(TestCase):
(c4.pk, 'Fourth'),
])
def test_choices_bool(self):
f = forms.ModelChoiceField(Category.objects.all(), empty_label=None)
self.assertIs(bool(f.choices), True)
Category.objects.all().delete()
self.assertIs(bool(f.choices), False)
def test_choices_bool_empty_label(self):
f = forms.ModelChoiceField(Category.objects.all(), empty_label='--------')
Category.objects.all().delete()
self.assertIs(bool(f.choices), True)
def test_deepcopies_widget(self):
class ModelChoiceForm(forms.Form):
category = forms.ModelChoiceField(Category.objects.all())