Return display_name in ChoiceField

前端 未结 3 1880
耶瑟儿~
耶瑟儿~ 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:34

    previous answers helped me a lot but not worked for me as I use Django version 3 and DRF version 3.11 , so I came up with this:

    # models.py
    class Ball(models.Model):
        
        class Types(models.TextChoice):
            VOLLYBALL = 'VB', gettext_lazy('VollyBall')
            FOOTBALL = 'FB', gettext_lazy('FootBall')
    
        type = models.CharField(max_length=2, choices=Types.choices)
    
    # serializers.py
    
    class CustomChoiceField(serializers.ChoiceField):
    
        def to_representation(self, value):
            if value in ('', None):
                return value
    
            choice_dict = {str(key): key.label for key in self.choices}
            return choice_dict.get(str(value), value)
    
        def to_internal_value(self, data):
            if data == '' and self.allow_blank:
                return ''
    
            try:
                choice_dict = {key.label: str(key) for key in self.choices}
                return choice_dict[str(data)]
            except KeyError:
                self.fail('invalid_choice', input=data)
    
    class BallSerializer(serializers.ModelSerializer):
        type = CustomChoiceField(choices=Book.Types)
        
        class Meta:
            model = Book
            fields = ['type']
    
    

提交回复
热议问题