Skip to content

Instantly share code, notes, and snippets.

@surenkov
Created October 21, 2019 14:43
Show Gist options
  • Save surenkov/2bf9669c25dc4a540dc9610ebede897c to your computer and use it in GitHub Desktop.
Save surenkov/2bf9669c25dc4a540dc9610ebede897c to your computer and use it in GitHub Desktop.
ChoiceEnum backport (simplified) for Django < 3.0
from enum import EnumMeta, Enum
__all__ = ['ChoiceEnum']
class ChoiceEnumMeta(EnumMeta):
def __iter__(cls):
return ((tag.value, tag.name) for tag in super().__iter__())
@property
def choices(cls):
return tuple(iter(cls))
class ChoiceEnum(Enum, metaclass=ChoiceEnumMeta):
"""Enum class which can be used in Django model field `choices=` :
>>> class SomeType(int, ChoiceEnum):
>>> TypeA = 1
>>> TypeB = 2
>>>
>>> from django.db import models
>>> class MyModel(models.Model):
>>> type = models.IntegerField(choices=SomeType.choices)
>>>
>>> m = MyModel(type=SomeType.TypeA)
>>> m.save()
>>> assert m.type == SomeType.TypeA
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment