Introduced ChoiceFieldSerializer for choice fields

This commit is contained in:
Jeremy Stretch
2017-02-08 16:00:42 -05:00
parent 6f3c3b6d61
commit 7040086201
3 changed files with 41 additions and 14 deletions

View File

@@ -1,5 +1,5 @@
from rest_framework.exceptions import APIException
from rest_framework.serializers import ModelSerializer
from rest_framework.serializers import Field
WRITE_OPERATIONS = ['create', 'update', 'partial_update', 'delete']
@@ -10,6 +10,22 @@ class ServiceUnavailable(APIException):
default_detail = "Service temporarily unavailable, please try again later."
class ChoiceFieldSerializer(Field):
"""
Represent a ChoiceField as a list of (value, label) tuples.
"""
def __init__(self, choices, **kwargs):
self._choices = choices
super(ChoiceFieldSerializer, self).__init__(**kwargs)
def to_representation(self, obj):
return self._choices[obj]
def to_internal_value(self, data):
return getattr(self._choices, data)
class WritableSerializerMixin(object):
"""
Allow for the use of an alternate, writable serializer class for write operations (e.g. POST, PUT).