How to Change Choices for Field in Django REST Framework
As usual for django forms common way to change choices for some field it’s overwrite __init__
method of form and replace self.fields['<field name>'].choices
. But it doesn’t work for django-rest-framework serializers.ChoiceField
.
For serializers.ChoiceField
you can again overwrite __init__
method and replace data in self.fields['<field name>'].choice_strings_to_values
where have to be dict where key is string representation of choices “key” and value is choices “key”.
like:
self.fields['fieldname'].choice_strings_to_values = {
str(key): key
for key, value in self.get_fieldname_choices()
}