I am trying to create an enumeration field in Django that after a GET request will return a text representation of the enumeration and on a POST or PATCH request, converts the text representation into an appropriate integer before saving.
transform_<field>()
works well for converting the integer enum value to the corresponding string, but I cannot figure out how best to convert the string to this corresponding integer, except hacking
validate_<field>()
method.
Is there a better way to do this? See code below
Model 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
python django django-rest-framework
Roger Thomas
source share