from collections import namedtuple
from django.db.models import *
def _get_field_choices(named):
"""
Namedtuple expected, return Django field choices
"""
dictionary = named._asdict()
return [(v, k) for (k, v) in dictionary.items()]
def get_named_choices(name, choices):
choices = namedtuple(name, choices)(*range(len(choices)))
return _get_field_choices(choices)
class Photo(Model):
_image_types = {
'COLOUR' : 0,
'BLACKWHITE' : 1,
'MONOCHROME' : 2,
'UNKNOWN' : 9,
}
IMAGE_TYPE = get_named_choices('ImageType', _image_types)
image_type = PositiveSmallIntegerField(
default=0,
choices=get_field_choices(IMAGE_TYPE)
)
"""
usage: myphoto.image_type = Photo.IMAGE_TYPE.BLACKWHITE
"""
Comments
CORRECTION (sorry)
def get_named_choices(name, choices): return namedtuple(name, choices)(*range(len(choices)))
#
class Property: def init(self, kwd): for (key, val) in kwd.iteritems(): if isinstance(val, dict): val = Property(val) self.dict[key] = val
#
#