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

CanonicalNameEnumField does not serialize to JSON correctly #66

Open
brennan-nc opened this issue May 15, 2019 · 1 comment
Open

CanonicalNameEnumField does not serialize to JSON correctly #66

brennan-nc opened this issue May 15, 2019 · 1 comment

Comments

@brennan-nc
Copy link

After running django's dumpdata management command with format json (using Django's default json serializer), I've noticed that CanonicalNameEnumField serializes to its display name. This appears to be happening because CanonicalNameEnumField inherits from CharField, and CharField's default serialization strategy is to use __unicode__. __unicode__ returns the canonical enum's display_name, rather than the canonical name. This behavior makes sense, since when the enum is displayed, its display name is what's wanted, but I don't think it makes sense for a serialization strategy.

After running dumpdata, when you try to load this data, the de-serialization fails because it looks for a canonical name matching the serialized display name.

I'm wondering if the current strategy for converting to a db value doesn't work when dumping to JSON? As far as I know, these are being stored in our database correctly with their canonical value, so I think this is specifically an issue with serializing to JSON.

I've found that overriding the method value_to_string resolves this issue (as described here in the Django docs): https://docs.djangoproject.com/en/1.11/howto/custom-model-fields/#converting-field-data-for-serialization

Adding that exact implementation described there resolves the issues and allows it to be both serialized and de-serialized. So in this file: django_richenum/models/fields.py if you add the following method implementation to the CanonicalNameEnumField class, you get the behavior that I think is wanted.

def value_to_string(self, obj):
        value = self.value_from_object(obj)
        return self.get_prep_value(value)

I'm not sure if there would be any other negative consequences associated with overriding value_to_string.

I'm using django 1.11, python 2.7, django-rich-enum 3.3.1.

@dhui
Copy link
Contributor

dhui commented May 16, 2019

I think overriding value_to_string() is safe...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants