choices.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. class ChoiceSetMeta(type):
  2. """
  3. Metaclass for ChoiceSet
  4. """
  5. def __call__(cls, *args, **kwargs):
  6. # Django will check if a 'choices' value is callable, and if so assume that it returns an iterable
  7. return getattr(cls, 'CHOICES', ())
  8. def __iter__(cls):
  9. choices = getattr(cls, 'CHOICES', ())
  10. return iter(choices)
  11. class ChoiceSet(metaclass=ChoiceSetMeta):
  12. CHOICES = list()
  13. LEGACY_MAP = dict()
  14. @classmethod
  15. def slug_to_id(cls, slug):
  16. """
  17. Return the legacy integer value corresponding to a slug.
  18. """
  19. return cls.LEGACY_MAP.get(slug)
  20. @classmethod
  21. def id_to_slug(cls, legacy_id):
  22. """
  23. Return the slug value corresponding to a legacy integer value.
  24. """
  25. if legacy_id in cls.LEGACY_MAP.values():
  26. # Invert the legacy map to allow lookup by integer
  27. legacy_map = dict([
  28. (id, slug) for slug, id in cls.LEGACY_MAP.items()
  29. ])
  30. return legacy_map.get(legacy_id)