Skip to content

Commit

Permalink
Refs #28312 -- Added an optimized __bool__() to ModelChoiceIterator.
Browse files Browse the repository at this point in the history
COUNT is more expensive than EXISTS; use the latter when possible.
  • Loading branch information
francoisfreitag authored and timgraham committed Apr 23, 2018
1 parent 3fca95e commit d1413c5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
3 changes: 3 additions & 0 deletions django/forms/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,9 @@ def __len__(self):
# 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))

Expand Down
11 changes: 11 additions & 0 deletions tests/model_forms/test_modelchoicefield.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,17 @@ def test_choices_freshness(self):
(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())
Expand Down

0 comments on commit d1413c5

Please sign in to comment.