Skip to content

CanonicalNameEnumField does not serialize to JSON correctly #66

@brennan-nc

Description

@brennan-nc

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions