I’m constantly doing the following pattern in Django:
class MyModel(models.Model):
FOO = 1
BAR = 2
GOO = 3
BLAH_TYPES = (
(FOO, 'Foodally boogaly'),
(BAR, 'Bar bar bar bar'),
(GOO, 'Goo goo gaa gaa'),
)
TYPE_FOR_ID = dict(BLAH_TYPES)
ID_FOR_TYPE = dict(zip(TYPE_FOR_ID.values(), TYPE_FOR_ID.keys()))
blah = models.IntegerField(choices=BLAH_TYPES)
Is there a good pattern that other people follow that achieves the same effect (i.e. I have access to constants with names and dictionaries that go both ways) without so much code?
Carl Meyer’s django-model-utils library has an excellent solution for this – the Choices class, which allows you to declare a list of choices with access via human-readable attributes.