[Solved]-How to pass choice display name to model serialize in Django REST framework?

34👍

you can use fields source with get_FOO_display

class TransferCostSerializer(serializers.ModelSerializer):
    destination_display = serializers.CharField(
        source='get_destination_display'
    )

3👍

just place get_destination_display withoput () in fields. like this:

class TransferCostSerializer(serializers.ModelSerializer):
    class Meta:
        model = TransferCost
        fields = ('id', 'get_destination_display', 'total_cost', 'is_active',)

0👍

In case you want to have the values of all model fields with choices to be returned as display values, following worked out for me:


from rest_framework import serializers
from django.core.exceptions import FieldDoesNotExist

class TransferCostSerializer(serializers.ModelSerializer):
    class Meta:
        model = TransferCost
        fields = ('id', 'destination', 'total_cost', 'is_active',)

    def to_representation(self, instance):
        """
        Overwrites choices fields to return their display value instead of their value.
        """
        data = super().to_representation(instance)
        for field in data:
            try:
                if instance._meta.get_field(field).choices:        
                    data[field] = getattr(instance, "get_" + field + "_display")()
            except FieldDoesNotExist:
                pass
        return data

The other solutions dropped auto generated meta-information of the model fields, e.g., translated labels.

Leave a comment