DRF : how to get the verbose name for choices?

Viewed 1434

Let's say I have this model:

class Student(models.Model):
    YEAR_IN_SCHOOL_CHOICES = (
        (FR, 'Freshman'),
        (SO, 'Sophomore'),
        (JU, 'Junior'),
        (S, 'Senior'),
    )
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

If I use DRF to expose the value for the year_in_school field, I get the first parameter of the choice, for example: "FR".

How can I expose the second parameter "Freshman" instead of "FR"?

2 Answers

You can use model's get_FOO_display method as source of serializer's field:

year_in_school = serializers.CharField(source='get_year_in_school_display')

In addition to the @neverwalkaloner answer (if for some reason you prefer to do it differently), you can also achieve the same behavior by overriding the to_representation method of the serializer, to use the get_FOO_display method of the instance:

def to_representation(self, instance):
    ret = super().to_representation(instance)
    ret['year_in_school'] = instance.get_year_in_school_display()
    return ret
Related