EN RU

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:

1
2
3
4
self.fields['fieldname'].choice_strings_to_values = {
    str(key): key
    for key, value in self.get_fieldname_choices()
}
    2016-08-26 19:00:26      django rest-framework