Django Model Choices using Python Enum
Python 3.4 introduced enums types which seem tailor made for use with django model choices. For some reason there seemed no examples to do this, but it’s relatively simple with some tricks (you may call them warts, django needs to enable this better). These have been back ported to prior python versions via the enum34 package (“pip install enum34”).
In this example, we’ll use an IntEnum to associate a variable with an integer value. For django, this means that the database contains integers, though we have a descriptive text for each choice. This is desirable, as we can abstract the name of the variable from the actual value. If you change / refactor the name, the existing values will simply remain the same.
Here’s the model definition:
from enum import IntEnum, unique def django_enum(cls): # decorator needed to enable enums in django templates cls.do_not_call_in_templates =
Continue reading →