如何在Django REST框架中将选择显示名称传递给模型序列化?

Vic*_*tak 6 python django django-rest-framework

我的env是Django 2.0.3,DRF 3.8.2和Python 3.6.4.

我有一个模型serializers.py:

class TransferCostSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        field_view = super().to_representation(instance)
        if field_view['is_active']:
            return field_view
        return None

    class Meta:
        model = TransferCost
        fields = ('id', 'destination', 'total_cost', 'is_active',)
Run Code Online (Sandbox Code Playgroud)

where destinationfield是3个元素的选择字段:

DESTINATION = (
    ('none', _('I will drive by myself')),
    ('transfer_airport', _('Only from airport')),
    ('transfer_round_trip', _('Round trip')),
)
Run Code Online (Sandbox Code Playgroud)

这是我的models.py:

class TransferCost(models.Model):

    destination = models.CharField(
        _('Transfer Destination'), choices=DESTINATION, max_length=55
    )
    total_cost = models.PositiveIntegerField(
        _('Total cost'), default=0
    )
    is_active = models.BooleanField(_('Transfer active?'), default=True)

    class Meta:
        verbose_name = _('Transfer')
        verbose_name_plural = _('Transfers')

    def __str__(self):
        return _('Transfer {}').format(self.destination)
Run Code Online (Sandbox Code Playgroud)

..我这样返回JSON:

[
    {
        id: 1,
        destination: "transfer_airport",
        total_cost: 25,
        is_active: true
    },
    {
        id: 2,
        destination: "transfer_round_trip",
        total_cost: 45,
        is_active: true
    }
]
Run Code Online (Sandbox Code Playgroud)

如何destination用他的显示名称返回字段?例如:

[
    {
        id: 1,
        destination_display: "Only from airport",
        destination: "transfer_round_trip",
        total_cost: 25,
        is_active: true
    },
    {
        id: 2,
        destination_display: "Round trip",
        destination: "transfer_round_trip",
        total_cost: 45,
        is_active: true
    }
]
Run Code Online (Sandbox Code Playgroud)

将是巨大的,有什么样get_FOO_display()serializers.py,但它不工作.我需要这个东西,因为我通过Vue.js动态渲染表单(作为v-for选择列表).

Bea*_*own 10

您可以使用字段源get_FOO_display

class TransferCostSerializer(serializers.ModelSerializer):
    destination_display = serializers.CharField(source='get_destination_display')
Run Code Online (Sandbox Code Playgroud)