summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSarah Boyce <42296566+sarahboyce@users.noreply.github.com>2024-09-17 12:40:21 +0200
committerSarah Boyce <42296566+sarahboyce@users.noreply.github.com>2024-09-18 16:45:53 +0200
commitae1ee24178ecd53ac5ef3fc2055e4be8b9602ac9 (patch)
tree1412f68d1d4999797e56ad394ccbb92c266b893c
parent9ca1f6eff6f19d1ae074d289c6c4209073351805 (diff)
Fixed #35766 -- Handled slices in BaseChoiceIterator.
-rw-r--r--django/utils/choices.py5
-rw-r--r--tests/model_fields/tests.py27
2 files changed, 30 insertions, 2 deletions
diff --git a/django/utils/choices.py b/django/utils/choices.py
index 7f40bce510..6b355d2324 100644
--- a/django/utils/choices.py
+++ b/django/utils/choices.py
@@ -21,8 +21,9 @@ class BaseChoiceIterator:
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))
diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py
index 36e54d4b8b..3d856d36c5 100644
--- a/tests/model_fields/tests.py
+++ b/tests/model_fields/tests.py
@@ -183,6 +183,33 @@ class ChoicesTests(SimpleTestCase):
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, [])