Django Rest Framework with ChoiceField

前端 未结 8 1928
轮回少年
轮回少年 2020-12-02 06:01

I have a few fields in my user model that are choice fields and am trying to figure out how to best implement that into Django Rest Framework.

Below is some simplifi

8条回答
  •  抹茶落季
    2020-12-02 06:17

    Probalbly you need something like this somewhere in your util.py and import in whichever serializers ChoiceFields are involved.

    class ChoicesField(serializers.Field):
        """Custom ChoiceField serializer field."""
    
        def __init__(self, choices, **kwargs):
            """init."""
            self._choices = OrderedDict(choices)
            super(ChoicesField, self).__init__(**kwargs)
    
        def to_representation(self, obj):
            """Used while retrieving value for the field."""
            return self._choices[obj]
    
        def to_internal_value(self, data):
            """Used while storing value for the field."""
            for i in self._choices:
                if self._choices[i] == data:
                    return i
            raise serializers.ValidationError("Acceptable values are {0}.".format(list(self._choices.values())))
    

提交回复
热议问题