For anyone finding this after the fact, this has been answered in the PR.
https://github.com/encode/django-rest-framework/pull/6854
On Friday, August 2, 2019 at 12:07:46 PM UTC-7, Owen Niles wrote:
>
> I have written the following code in the Django shell:
>
> from rest_framework import serializers
>
> class MySerializer(serializers.Serializer):
> choice = serializers.ChoiceField(choices=[(1, 'One'), (2, 'Two'), (3,
> 'Three')], required=True)
>
> serializer = MySerializer(data={'choice': 'One'})
> serializer.is_valid()
> serializer.validated_data
>
> Before I executed the code, I expected serializer.is_valid() to return
> True and for serializer.validated_data to contain:
>
> OrderedDict([('choice': 1)])
>
> However, it seems that I misunderstood the deserialization behavior of
> rest_framework.serializers.ChoiceField because I was surprised to
> discover that serializer.is_valid() returns False and that
> serializer.validated_data contains:
>
> {}
>
> When I call serializer.is_valid(raise_exception=True), the traceback
> sheds some more light on the situation.
>
> Traceback (most recent call last):
> File "<console>", line 1, in <module>
> File "/path/to/rest_framework/serializers.py", line 243, in is_valid
> raise ValidationError(self.errors)
> rest_framework.exceptions.ValidationError: {'choice':
> [ErrorDetail(string='"One"
> is not a valid choice.', code='invalid_choice')]}
>
> Furthermore, when I instantiate serializer as follows:
>
> serializer = MySerializer(data={'choice': 1})
>
> serializer.is_valid() *does* return True and serializer.validated_data
> contains
>
> OrderedDict([('choice': 1)])
>
> So I have two questions:
>
> 1) Is this the intended deserialization behavior of
> rest_framework.serializers.ChoiceField?
> 2) If so, why does each choice have a separate key and display_name
> described here
> <https://www.django-rest-framework.org/api-guide/fields/#choicefield> or
> how can one resolve a display_name to a key without doing it manually?
> It's not that I have a *problem* with doing it manually, but if I *were *to
> do it manually, I would feel like I was doing something wrong because I
> glanced at the source code and it looks like there is a way to do it
> automatically.
>
--
You received this message because you are subscribed to the Google Groups
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-rest-framework/b66e92dc-27f7-4000-ad5b-72bfcef00036%40googlegroups.com.