Return display_name in ChoiceField

 ̄綄美尐妖づ 提交于 2019-12-07 20:33:37

问题


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 field, like that:

MyModel(models.Model):
     KEY1 = 'Key1'
     KEY2 = 'Key2'
     ATTRIBUTE_CHOICES = (
         (KEY1, 'Label 1'),
         (KEY2, 'Label 2'))
     attribute = models.CharField(max_length=4, 
                                  choices=ATTRIBUTE_CHOICES, default=KEY1)

My problem is that by default DRF always returns (and accept) the key of these choices for JSON messages (see here), but I would like to use the label instead, because I think it's more consistent and clear to unterstand for who will use those APIs. Any suggestion?


回答1:


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.




回答2:


There's no way other than overriding your serializer. Please take a look here, to see how it can be done.



来源:https://stackoverflow.com/questions/34534239/return-display-name-in-choicefield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!