Return display_name in ChoiceField

前端 未结 3 1881
耶瑟儿~
耶瑟儿~ 2021-01-15 03:06

I\'m implementing some REST API in DRF with ModelViewSet and ModelSerializer. All my APIs use the JSON format and some of my models use ChoiceField

3条回答
  •  佛祖请我去吃肉
    2021-01-15 03:32

    I found a possible solution, namely defining my own field as follow:

    class MyChoiceField(serializers.ChoiceField):
    
        def to_representation(self, data):
            if data not in self.choices.keys():
                self.fail('invalid_choice', input=data)
            else:
                return self.choices[data]
    
        def to_internal_value(self, data):
            for key, value in self.choices.items():
                if value == data:
                     return key
            self.fail('invalid_choice', input=data)
    

    It works the same way as to ChoiceField, but returns and accepts labels instead of keys.

提交回复
热议问题