Last active
January 26, 2023 13:00
-
-
Save Cerebro92/27ea95d3f8d64411d8f6bc327595e909 to your computer and use it in GitHub Desktop.
Demonstrates extensible Integer Choice.
This file contains 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 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