Tweaked ChoiceFieldSerializer to display a field as (value, label)

This commit is contained in:
Jeremy Stretch 2017-02-16 14:37:21 -05:00
parent b71566f206
commit 21281789e0
2 changed files with 5 additions and 5 deletions

View File

@ -103,7 +103,7 @@ class RackSerializer(CustomFieldModelSerializer):
tenant = NestedTenantSerializer() tenant = NestedTenantSerializer()
role = NestedRackRoleSerializer() role = NestedRackRoleSerializer()
type = ChoiceFieldSerializer(choices=RACK_TYPE_CHOICES) type = ChoiceFieldSerializer(choices=RACK_TYPE_CHOICES)
# width = ChoiceFieldSerializer(choices=RACK_WIDTH_CHOICES) width = ChoiceFieldSerializer(choices=RACK_WIDTH_CHOICES)
class Meta: class Meta:
model = Rack model = Rack

View File

@ -12,18 +12,18 @@ class ServiceUnavailable(APIException):
class ChoiceFieldSerializer(Field): class ChoiceFieldSerializer(Field):
""" """
Represent a ChoiceField as a list of (value, label) tuples. Represent a ChoiceField as (value, label).
""" """
def __init__(self, choices, **kwargs): def __init__(self, choices, **kwargs):
self._choices = choices self._choices = {k: v for k, v in choices}
super(ChoiceFieldSerializer, self).__init__(**kwargs) super(ChoiceFieldSerializer, self).__init__(**kwargs)
def to_representation(self, obj): def to_representation(self, obj):
return self._choices[obj] return obj, self._choices[obj]
def to_internal_value(self, data): def to_internal_value(self, data):
return getattr(self._choices, data) return self._choices.get(data)
class WritableSerializerMixin(object): class WritableSerializerMixin(object):