Skip to content

Instantly share code, notes, and snippets.

@phill-tornroth
Created May 18, 2011 21:56
Show Gist options
  • Save phill-tornroth/979666 to your computer and use it in GitHub Desktop.
Save phill-tornroth/979666 to your computer and use it in GitHub Desktop.
Thoughts on a nicer choices field.
class Choices(object):
def __getattr__(self, item):
if str(item).isdigit():
try:
return self.__getitem__(item)
except KeyError:
pass
result = self.value_for_name(item)
if result == None:
raise AttributeError(item)
else:
return result
def value_for_name(self, choice_name):
for i, name in self._choices:
if name == choice_name:
return i
def __init__(self, *args):
self._choices = args
def __len__(self):
return len(self._choices)
def __getitem__(self, key):
return self._choices[key]
def __setitem__(self, key, value):
return self._choices.__setitem__(key, value)
def __delitem__(self, key):
return self.__delitem__(key)
def __iter__(self):
return self._choices.__iter__()
def __contains__(self, item):
return item in self._choices
COLOR_CHOICES = Choices(
(0, 'red'),
(1, 'blue'),
)
class MyModel(models.Model):
color = models.PositiveSmallIntegerField(choices=COLOR_CHOICES)
i = MyModel()
i.color = COLOR_CHOICES.red
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment