问题描述
我在我的用户模型中有几个字段是选择字段,我试图找出如何最好地将它们实现到Django Rest Framework中。
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 simplified code to show what I'm doing.
# models.py
class User(AbstractUser):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
# serializers.py
class UserSerializer(serializers.ModelSerializer):
gender = serializers.CharField(source='get_gender_display')
class Meta:
model = User
# viewsets.py
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
我想要做的是让get / post / put方法使用选择的显示值字段而不是代码,看起来像下面的JSON。
Essentially what I'm trying to do is to have the get/post/put methods use the display value of the choice field instead of the code, looking something like the below JSON.
{
'username': 'newtestuser',
'email': '[email protected]',
'first_name': 'first',
'last_name': 'last',
'gender': 'Male'
// instead of 'gender': 'M'
}
我该怎么做呢?以上代码不起作用之前我有这样的工作为GET,但是POST / PUT它给我的错误。我正在寻找一般的建议,如何做到这一点,似乎这是常见的事情,但我找不到例子。或者我正在做一些非常错误的事情。
How would I go about doing that? The above code does not work. Before I had something like this working for GET, but for POST/PUT it was giving me errors. I'm looking for general advice on how to do this, it seems like it would be something common, but I can't find examples. Either that or I'm doing something terribly wrong.
推荐答案
Django提供获取字段的可读值的方法:
Django provides the Model.get_FOO_display
method to get the "human-readable" value of a field:
class UserSerializer(serializers.ModelSerializer):
gender = serializers.SerializerMethodField()
class Meta:
model = User
def get_gender(self,obj):
return obj.get_gender_display()
这篇关于Django休息框架与ChoiceField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!