Serialize and De-serialize a Django Enum field to

2019-03-13 12:55发布

问题:

I'm trying to create an enum field in Django that, upon a GET request will return the text representation of the enum and upon a POST or PATCH request will convert the text representation to the corresponding integer before saving.

The

transform_<field>()

method works nicely for converting the integer enum value to its corresponding string, but I can't figure out a better way of converting the string into it's corresponding integer other than hacking the

validate_<field>()

method.

Is there a better way of doing this? Please see code below

Models file

class Status(enum.Enum):
    RUNNING = 0
    COMPLETED = 1

    labels = {
         RUNNING: 'Running',
         COMPLETED: 'Completed'
    }

    translation = {v: k for k, v in labels.iteritems()}

class Job(models.Model):
    status = enum.EnumField(Status)

Serializer

class JobSeralizer(serializers.ModelSerailzer):
    status = seralizers.CharField(max_length=32, default=Status.QUEUED)

    def transform_status(self, obj, value):
        return JobStatus.labels[value]

    def validate_status(self, attrs, source):
        """Allow status to take numeric or character representation of status
        """
        status = attrs[source]
        if status in JobStatus.translation:
            attrs[source] = JobStatus.translation[status]
        elif status.isdigit():
            attrs[source] = int(status)
        else:
            raise serializers.ValidationError("'%s' not a valid status" % status)
        return attrs

回答1:

As OP stated, you can do this easily using custom fields in drf v3.x. Here's a quick example of a generic custom field used to convert values <-> labels (e.g. enum values <-> textual representation):

class KeyValueField(serializers.Field):
    """ A field that takes a field's value as the key and returns
    the associated value for serialization """

    labels = {}
    inverted_labels = {}

    def __init__(self, labels, *args, **kwargs):
        self.labels = labels
        # Check to make sure the labels dict is reversible, otherwise
        # deserialization may produce unpredictable results
        inverted = {}
        for k, v in labels.iteritems():
            if v in inverted:
                raise ValueError(
                    'The field is not deserializable with the given labels.'
                    ' Please ensure that labels map 1:1 with values'
                )
            inverted[v] = k
        self.inverted_labels = inverted
        return super(KeyValueField, self).__init__(*args, **kwargs)

    def to_representation(self, obj):
        if type(obj) is list:
            return [self.labels.get(o, None) for o in obj]
        else:
            return self.labels.get(obj, None)

    def to_internal_value(self, data):
        if type(data) is list:
            return [self.inverted_labels.get(o, None) for o in data]
        else:
            return self.inverted_labels.get(data, None)

The field initialization would look something like this:

class MySerializer(serializers.Serializer):
    afield = KeyValueField(labels={0:'enum text 0', 1:'enum text 1'})