Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to serialize enum by names #78

Open
souliane opened this issue Oct 5, 2017 · 2 comments
Open

Allow to serialize enum by names #78

souliane opened this issue Oct 5, 2017 · 2 comments

Comments

@souliane
Copy link

souliane commented Oct 5, 2017

Would be nice to add an option to serialize enum name instead of value.
I use such objects:

class FrequencyChoices(Enum):
    monthly = relativedelta.relativedelta(months=1)
    quarterly = relativedelta.relativedelta(months=3)

The values are not serializable so I need to serialize the name instead. Maybe the best would just be to rename the option ints_as_names and do not constraint its usage to enums storing int values. I can think about other applications where it could be preferable to serialize the name, even if the value is also serializable:

class CurrencyChoices(Enum):
    euro = "€"
    us_dollar = "$"
@ADR-007
Copy link

ADR-007 commented Jan 10, 2019

Hi!
I do it in the next way:

class Frequency(Enum):
    MONTHLY = 'monthly', relativedelta.relativedelta(months=1)
    QUARTERLY = 'quarterly', relativedelta.relativedelta(months=3)

    def __new__(cls, value, duration):
        obj = object.__new__(cls)
        obj._value_ = value
        obj._duration_ = duration
        return obj

    @property
    def duration(self) -> relativedelta.relativedelta:
        return self._duration_


print(Frequency.MONTHLY.value)
print(Frequency.MONTHLY.duration)

@akx akx self-assigned this Jan 17, 2020
@akx
Copy link
Contributor

akx commented Jan 17, 2020

Hmm, yeah, this isn't restricted to DRF serialization alone.

Trying

class Frequency(Enum):
    month = timedelta(days=30)
    quarter = timedelta(days=365 // 4)

class Model(...):
    frequency = EnumField(Frequency, default=Frequency.month)

will also lead to all sorts of errors since timedelta()s can't be stuffed into CharFields.

@akx akx removed their assignment Jan 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants