使用ChoiceField的Django Rest框架

时间:2015-03-09 15:08:55

标签: django django-rest-framework

我的用户模型中有一些字段是选择字段,我试图弄清楚如何最好地将其实现到Django Rest Framework中。

下面是一些简化的代码,用于展示我正在做的事情。

# 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。

{
  'username': 'newtestuser',
  'email': 'newuser@email.com',
  'first_name': 'first',
  'last_name': 'last',
  'gender': 'Male'
  // instead of 'gender': 'M'
}

我该怎么做呢?上面的代码不起作用。在我有这样的东西为GET工作之前,但对于POST / PUT它给了我错误。我正在寻找关于如何做到这一点的一般建议,看起来它会是常见的,但我找不到例子。或者我正在做一些非常错误的事情。

8 个答案:

答案 0 :(得分:84)

Django提供了Model.get_FOO_display方法来获取字段的“人类可读”值:

class UserSerializer(serializers.ModelSerializer):
    gender = serializers.SerializerMethodField()

    class Meta:
        model = User

    def get_gender(self,obj):
        return obj.get_gender_display()

最新的DRF(3.6.3) - 最简单的方法是:

gender = serializers.CharField(source='get_gender_display')

答案 1 :(得分:14)

我建议将django-models-utils与自定义DRF serializer field

一起使用

代码变为:

# models.py
from model_utils import Choices

class User(AbstractUser):
    GENDER = Choices(
       ('M', 'Male'),
       ('F', 'Female'),
    )

    gender = models.CharField(max_length=1, choices=GENDER, default=GENDER.M)


# serializers.py 
from rest_framework import serializers

class ChoicesField(serializers.Field):
    def __init__(self, choices, **kwargs):
        self._choices = choices
        super(ChoicesField, self).__init__(**kwargs)

    def to_representation(self, obj):
        return self._choices[obj]

    def to_internal_value(self, data):
        return getattr(self._choices, data)

class UserSerializer(serializers.ModelSerializer):
    gender = ChoicesField(choices=User.GENDER)

    class Meta:
        model = User

# viewsets.py
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

答案 2 :(得分:7)

顺便说一句,你需要util.py中的某个地方输入这样的内容,并导入所涉及的序列化ChoiceFields

class ChoicesField(serializers.Field):
    """Custom ChoiceField serializer field."""

    def __init__(self, choices, **kwargs):
        """init."""
        self._choices = OrderedDict(choices)
        super(ChoicesField, self).__init__(**kwargs)

    def to_representation(self, obj):
        """Used while retrieving value for the field."""
        return self._choices[obj]

    def to_internal_value(self, data):
        """Used while storing value for the field."""
        for i in self._choices:
            if self._choices[i] == data:
                return i
        raise serializers.ValidationError("Acceptable values are {0}.".format(list(self._choices.values())))

答案 3 :(得分:6)

以下解决方案适用于任何带选项的字段,无需在序列化程序中为每个字段指定自定义方法:

from rest_framework import serializers

class ChoicesSerializerField(serializers.SerializerMethodField):
    """
    A read-only field that return the representation of a model field with choices.
    """

    def to_representation(self, value):
        # sample: 'get_XXXX_display'
        method_name = 'get_{field_name}_display'.format(field_name=self.field_name)
        # retrieve instance method
        method = getattr(value, method_name)
        # finally use instance method to return result of get_XXXX_display()
        return method()

示例:

下式给出:

class Person(models.Model):
    ...
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

使用:

class PersonSerializer(serializers.ModelSerializer):
    ...
    gender = ChoicesSerializerField()

接收:

{
    ...
    'gender': 'Male'
}

而不是:

{
    ...
    'gender': 'M'
}

答案 4 :(得分:4)

DRF 3.1起,有一个名为customizing field mapping的新API。我用它将默认的ChoiceField映射更改为ChoiceDisplayField:

import six
from rest_framework.fields import ChoiceField


class ChoiceDisplayField(ChoiceField):
    def __init__(self, *args, **kwargs):
        super(ChoiceDisplayField, self).__init__(*args, **kwargs)
        self.choice_strings_to_display = {
            six.text_type(key): value for key, value in self.choices.items()
        }

    def to_representation(self, value):
        if value is None:
            return value
        return {
            'value': self.choice_strings_to_values.get(six.text_type(value), value),
            'display': self.choice_strings_to_display.get(six.text_type(value), value),
        }

class DefaultModelSerializer(serializers.ModelSerializer):
    serializer_choice_field = ChoiceDisplayField

如果您使用DefaultModelSerializer

class UserSerializer(DefaultModelSerializer):    
    class Meta:
        model = User
        fields = ('id', 'gender')

你会得到类似的东西:

...

"id": 1,
"gender": {
    "display": "Male",
    "value": "M"
},
...

答案 5 :(得分:3)

对此线程的更新,在最新版本的DRF中实际上有一个ChoiceField

因此,如果要返回display_name,您需要做的就是继承ChoiceField to_representation方法,如下所示:

from django.contrib.auth import get_user_model
from rest_framework import serializers

User = get_user_model()

class ChoiceField(serializers.ChoiceField):

    def to_representation(self, obj):
        return self._choices[obj]

class UserSerializer(serializers.ModelSerializer):
    gender = ChoiceField(choices=User.GENDER_CHOICES)

    class Meta:
        model = User

因此无需更改__init__方法或添加任何其他程序包。

答案 6 :(得分:0)

我发现soup boy的方法是最好的。虽然我建议继承serializers.ChoiceField而不是serializers.Field。这样,您只需要覆盖to_representation方法,其余方法就像常规的ChoiceField一样。

class DisplayChoiceField(serializers.ChoiceField):

    def __init__(self, *args, **kwargs):
        choices = kwargs.get('choices')
        self._choices = OrderedDict(choices)
        super(DisplayChoiceField, self).__init__(*args, **kwargs)

    def to_representation(self, obj):
        """Used while retrieving value for the field."""
        return self._choices[obj]

答案 7 :(得分:0)

我更喜欢@nicolaspanel的答案,以保持该字段可写。如果使用此定义而不是他的navigation,则在映射animation => {{1}的选择时,您将利用内置ChoiceField中的任何/所有基础结构}:

ChoiceField

@property重写是“丑陋的”,但我的目标始终是尽可能少地更改核心(以最大程度地实现前向兼容性)。

P.S。如果您想str,则DRF中有一个bug。最简单的解决方法是将以下内容添加到int

class MappedChoiceField(serializers.ChoiceField):

    @serializers.ChoiceField.choices.setter
    def choices(self, choices):
        self.grouped_choices = fields.to_choices_dict(choices)
        self._choices = fields.flatten_choices_dict(self.grouped_choices)
        # in py2 use `iteritems` or `six.iteritems`
        self.choice_strings_to_values = {v: k for k, v in self._choices.items()}

P.P.S。如果您有一堆都需要映射的选择字段,请利用@lechup指出的功能,然后将以下内容添加到allow_blank不是其{{1 }}):

MappedChoiceField