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

时间:2018-05-15 07:35:21

标签: 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',)

其中destination字段是3个元素的选择字段:

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

这是我的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)

..我这样返回JSON:

[
    {
        id: 1,
        destination: "transfer_airport",
        total_cost: 25,
        is_active: true
    },
    {
        id: 2,
        destination: "transfer_round_trip",
        total_cost: 45,
        is_active: true
    }
]

如何使用显示名称返回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
    }
]

get_FOO_display()中使用serializers.py之类的内容会很棒,但它不起作用。我需要这个东西,因为我通过Vue.js动态渲染表单(作为v-for选择列表)。

1 个答案:

答案 0 :(得分:8)

您可以将fields sourceget_FOO_display

一起使用
class TransferCostSerializer(serializers.ModelSerializer):
    destination_display = serializers.CharField(source='get_destination_display')