我的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
选择列表)。
答案 0 :(得分:8)
您可以将fields source与get_FOO_display
一起使用class TransferCostSerializer(serializers.ModelSerializer):
destination_display = serializers.CharField(source='get_destination_display')