Skip to content

Instantly share code, notes, and snippets.

@Cerebro92
Last active January 26, 2023 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cerebro92/27ea95d3f8d64411d8f6bc327595e909 to your computer and use it in GitHub Desktop.
Save Cerebro92/27ea95d3f8d64411d8f6bc327595e909 to your computer and use it in GitHub Desktop.
Demonstrates extensible Integer Choice.
from django.db import models
from django.utils.functional import classproperty
class InheritableIntegerChoicesMeta(type):
def __init__(cls, name, bases, attrs):
super().__init__(name, bases, attrs)
choices = []
for c in cls.mro():
choices += [(value, name) for name, value in c.__dict__.items() if not callable(value) and not name.startswith("__") and name != "choices"]
cls.choices = classproperty(lambda cls: choices)
class InheritableIntegerChoices(metaclass=InheritableIntegerChoicesMeta):
pass
class BaseChoices(InheritableIntegerChoices):
NONE = 0
class SMSChannels(BaseChoices):
SMS = 1
class EmailChannels(BaseChoices):
EMAIL = 2
class SMSEmailChannels(SMSChannels, EmailChannels):
SMS_EMAIL = 3
class MyModel(models.Model):
category1 = models.PositiveIntegerField(
choices=SMSEmailChannels.choices,
default=SMSEmailChannels.SMS_EMAIL,
)
category2 = models.PositiveIntegerField(
choices=SMSChannels.choices,
default=SMSChannels.SMS,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment