问题描述
我正在使用ModelViewSet
和ModelSerializer
在DRF中实现一些REST API.我所有的API都使用JSON格式,而我的某些模型则使用ChoiceField字段,例如:
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)
我的问题是,默认情况下,DRF始终返回(并接受)JSON消息的这些选择的键(请参阅此处),但我想改用标签,因为我认为不了解谁将使用这些API更加一致和明确.有什么建议吗?
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?
推荐答案
我找到了一种可能的解决方案,即按如下方式定义自己的字段:
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)
它的作用方式与ChoiceField
相同,但是返回并接受标签而不是键.
It works the same way as to ChoiceField
, but returns and accepts labels instead of keys.
这篇关于在ChoiceField中返回display_name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!