Opened 3 days ago

Last modified 5 hours ago

#35766 closed Bug

Choice iterator breaks when using slices — at Version 1

Reported by: David Owned by:
Component: Database layer (models, ORM) Version: 5.0
Severity: Normal Keywords:
Cc: Natalia Bidart, Nick Pope Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by David)

Currently the choice-iterator classes introduced in https://code.djangoproject.com/ticket/24561 are designed to work with index-based access.

   

class MyModel(models.Model):
  field = models.IntegerField(choices=lambda: range(10))


the_field = MyModel._meta.get_field("field")
the_field.choices[2]
#> 3

Since choices has been out for long time accepting there are libraries in which the field.choices attribute was used as it it was a tuple/list, which can be accessed also with slicing syntax (see sphinxcontrib-django ), this now raises an error:

the_field.choices[:2]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[13], line 1
----> 1 the_field.choices[:2]

File /opt/venv/lib/python3.10/site-packages/django/utils/choices.py:24, in BaseChoiceIterator.__getitem__(self, index)
     23 def __getitem__(self, index):
---> 24     if index < 0:
     25         # Suboptimally consume whole iterator to handle negative index.
     26         return list(self)[index]
     27     try:
TypeError: '<' not supported between instances of 'slice' and 'int'

The __getitem__ states that the management of key type should be handled in the implementation.

It should be choosen if slices are going to be supported or if only integers are going to be supported by this class.

Change History (1)

comment:1 by David, 3 days ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top