I have an array of choice fields. I want the human-readable text as a response instead of just numbers.
How to deserialize an array choice field in Django Rest Frameworks?
Response
"categories": [
1,
2
],
Expected Response
"categories": [
"Carpentry",
"Interior"
],
class ChoiceArrayField(ArrayField):
def formfield(self,**kwargs):
defaults = {
'form_class': forms.TypedMultipleChoiceField,
'choices': self.base_field.choices,
}
defaults.update(kwargs)
return super(ArrayField, self).formfield(**defaults)
Model.py
categories_choices = (
(1,"Carpentry"),
(2,"Interior"),
(3,"Furniture"),
(4,"Plumber"),
(5,"Electrican"),
(6,"Construction"),
(7,"Painting"),
(8,"Flooring"),
(9,"Yard Settings")
)
categories = ChoiceArrayField(
base_field = models.CharField(max_length=32,choices=categories_choices, null=True,blank=True),
default=list,
null=True, blank=True
)
Serializer.py
class ProfileSerializer(serializers.ModelSerializer):
phone_number = serializers.IntegerField(source='phone.phonenum')
id = serializers.IntegerField(source='phone.id')
class Meta:
exclude = ('phone',)
model = ProfileModel