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

lqfhib0f  于 2023-03-09  发布在  Go
关注(0)|答案(3)|浏览(138)

我的环境是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
    }
]

serializers.py中有get_FOO_display()这样的东西是很好的,但是它不起作用。我需要这个东西,因为我通过Vue.js动态呈现表单(作为v-for选择列表)。

gcuhipw9

gcuhipw91#

可以将字段源与get_FOO_display一起使用

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

pgpifvop2#

只需将带有输出()get_destination_display放入fields中,如下所示:

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

esbemjvw3#

如果你想有选择的所有模型字段的值作为显示值返回,下面为我工作:

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

其他解决方案丢弃了模型字段的自动生成的元信息,例如翻译的标签。

相关问题