Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF : how to get the verbose name for choices?

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"?

like image 645
Aurélien Avatar asked Sep 05 '18 10:09

Aurélien


1 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')
like image 130
neverwalkaloner Avatar answered Oct 09 '22 01:10

neverwalkaloner