Added get_<choice>_display function to ChoiceNum to easily display human readable option label.

This commit is contained in:
Jannis Leidel 2010-04-15 04:36:21 +02:00
parent 50919b9ff4
commit 1fce7073e2
3 changed files with 9 additions and 1 deletions

View file

@ -34,6 +34,7 @@ class ChoiceEnum(object):
for i, choice in enumerate(self.equalize(choices)):
self._choices += ((i, choice[0]),)
self._iter_choices += ((i, choice[1]),)
self.set_display(choice[0], choice[1])
self._choice_dict = dict(self._choices)
self._reverse_dict = dict(((i[1], i[0]) for i in self._choices))
@ -44,6 +45,9 @@ class ChoiceEnum(object):
else:
yield (choice, choice)
def set_display(self, name, value):
setattr(self, 'get_%s_display' % name.lower(), lambda: value)
def __iter__(self):
return iter(self._iter_choices)

View file

@ -6,7 +6,7 @@ INSTALLED_APPS = (
'django.contrib.contenttypes',
'model_utils',
'model_utils.tests',
)
)
DATABASE_ENGINE = 'sqlite3'

View file

@ -87,6 +87,8 @@ class ChoiceEnumTests(TestCase):
def test_iteration(self):
self.assertEquals(tuple(self.STATUS), ((0, 'DRAFT'), (1, 'PUBLISHED')))
def test_display(self):
self.assertEquals(self.STATUS.get_draft_display(), 'DRAFT')
class LabelChoiceEnumTests(ChoiceEnumTests):
def setUp(self):
@ -99,6 +101,8 @@ class LabelChoiceEnumTests(ChoiceEnumTests):
def test_iteration(self):
self.assertEquals(tuple(self.STATUS), ((0, 'draft'), (1, 'published'), (2, 'DELETED')))
def test_display(self):
self.assertEquals(self.STATUS.get_deleted_display(), 'DELETED')
class InheritanceCastModelTests(TestCase):
def setUp(self):