Created
October 21, 2019 14:43
-
-
Save surenkov/2bf9669c25dc4a540dc9610ebede897c to your computer and use it in GitHub Desktop.
ChoiceEnum backport (simplified) for Django < 3.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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