Skip to content

Commit

Permalink
Fixed #35766 -- Handled slices in BaseChoiceIterator.
Browse files Browse the repository at this point in the history
  • Loading branch information
sarahboyce committed Sep 18, 2024
1 parent 9ca1f6e commit ae1ee24
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
5 changes: 3 additions & 2 deletions django/utils/choices.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ def __eq__(self, other):
return super().__eq__(other)

def __getitem__(self, index):
if index < 0:
# Suboptimally consume whole iterator to handle negative index.
if isinstance(index, slice) or index < 0:
# Suboptimally consume whole iterator to handle slices and negative
# indexes.
return list(self)[index]
try:
return next(islice(self, index, index + 1))
Expand Down
27 changes: 27 additions & 0 deletions tests/model_fields/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,33 @@ def test_choices(self):
self.choices_from_callable.choices.func(), [(0, "0"), (1, "1"), (2, "2")]
)

def test_choices_slice(self):
for choices, expected_slice in [
(self.empty_choices.choices, []),
(self.empty_choices_bool.choices, []),
(self.empty_choices_text.choices, []),
(self.with_choices.choices, [(1, "A")]),
(self.with_choices_dict.choices, [(1, "A")]),
(self.with_choices_nested_dict.choices, [("Thing", [(1, "A")])]),
(self.choices_from_iterator.choices, [(0, "0"), (1, "1")]),
(self.choices_from_callable.choices.func(), [(0, "0"), (1, "1")]),
(self.choices_from_callable.choices, [(0, "0"), (1, "1")]),
]:
with self.subTest(choices=choices):
self.assertEqual(choices[:2], expected_slice)

def test_choices_negative_index(self):
for choices, expected_choice in [
(self.with_choices.choices, (1, "A")),
(self.with_choices_dict.choices, (1, "A")),
(self.with_choices_nested_dict.choices, ("Thing", [(1, "A")])),
(self.choices_from_iterator.choices, (2, "2")),
(self.choices_from_callable.choices.func(), (2, "2")),
(self.choices_from_callable.choices, (2, "2")),
]:
with self.subTest(choices=choices):
self.assertEqual(choices[-1], expected_choice)

def test_flatchoices(self):
self.assertEqual(self.no_choices.flatchoices, [])
self.assertEqual(self.empty_choices.flatchoices, [])
Expand Down

0 comments on commit ae1ee24

Please sign in to comment.