Django Rest Framework with ChoiceField

前端 未结 8 1950
轮回少年
轮回少年 2020-12-02 06:01

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 simplifi

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 06:16

    The following solution works with any field with choices, with no need to specify in the serializer a custom method for each:

    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()
    

    Example:

    given:

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

    use:

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

    to receive:

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

    instead of:

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

提交回复
热议问题