My env is Django 2.0.3, DRF 3.8.2 and Python 3.6.4.
I have a model in serializers.py
:
JavaScript
x
12
12
1
class TransferCostSerializer(serializers.ModelSerializer):
2
3
def to_representation(self, instance):
4
field_view = super().to_representation(instance)
5
if field_view['is_active']:
6
return field_view
7
return None
8
9
class Meta:
10
model = TransferCost
11
fields = ('id', 'destination', 'total_cost', 'is_active',)
12
Where destination
field is choice field of 3 elements:
JavaScript
1
6
1
DESTINATION = (
2
('none', _('I will drive by myself')),
3
('transfer_airport', _('Only from airport')),
4
('transfer_round_trip', _('Round trip')),
5
)
6
This is my models.py
:
JavaScript
1
17
17
1
class TransferCost(models.Model):
2
3
destination = models.CharField(
4
_('Transfer Destination'), choices=DESTINATION, max_length=55
5
)
6
total_cost = models.PositiveIntegerField(
7
_('Total cost'), default=0
8
)
9
is_active = models.BooleanField(_('Transfer active?'), default=True)
10
11
class Meta:
12
verbose_name = _('Transfer')
13
verbose_name_plural = _('Transfers')
14
15
def __str__(self):
16
return _('Transfer {}').format(self.destination)
17
..And I return JSON like this:
JavaScript
1
15
15
1
[
2
{
3
id: 1,
4
destination: "transfer_airport",
5
total_cost: 25,
6
is_active: true
7
},
8
{
9
id: 2,
10
destination: "transfer_round_trip",
11
total_cost: 45,
12
is_active: true
13
}
14
]
15
How to return destination
field with his display name? For example:
JavaScript
1
17
17
1
[
2
{
3
id: 1,
4
destination_display: "Only from airport",
5
destination: "transfer_round_trip",
6
total_cost: 25,
7
is_active: true
8
},
9
{
10
id: 2,
11
destination_display: "Round trip",
12
destination: "transfer_round_trip",
13
total_cost: 45,
14
is_active: true
15
}
16
]
17
Would be great to have something like get_FOO_display()
in serializers.py
, but it’s not working. I need this thing, because I render form dynamically via Vue.js (as v-for
select list).
Advertisement
Answer
you can use fields source with get_FOO_display
JavaScript
1
5
1
class TransferCostSerializer(serializers.ModelSerializer):
2
destination_display = serializers.CharField(
3
source='get_destination_display'
4
)
5