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/7a5d8869-e9e9-4e46-91d6-8f1261479967%40googlegroups.com.