Reputation: 55
I have a Django model Offer with field like name ... and bandwidth_value and bandwidth_unit. I use Django REST framework class ModelSerializer to serialize my model. I have :
{"id": 10,"max_devices":5,"bandwidth_value":"100.00","bandwidth_unit":"M"}
And I want to have ;
{"id": 10,"max_devices":5,"bandwidth":{"value":"100.00","unit":"M"}}
How can I do ?
Upvotes: 5
Views: 3853
Reputation: 55448
You can use a custom model serializer like below for your Offer
model:
class Offer(serializers.ModelSerializer):
class Meta:
model = Offer
fields = ('id', 'max_devices', 'bandwidth')
# We add a custom field called "bandwidth",
# which is served by a method in the serializer classs,
# that returns the format you want.
bandwidth = serializers.SerializerMethodField('get_bandwidth')
def get_bandwidth(self, obj):
return {'bandwidth': {'value': obj.bandwidth_value,
'unit': obj.bandwidth_unit}}
Upvotes: 5