2016-04-23 74 views
3

我有一個Django模型提供字段像名稱...和bandwidth_value和bandwidth_unit。我使用Django REST框架類ModelSerializer來序列化我的模型。 我有:Django Rest框架組字段在一起

{"id": 10,"max_devices":5,"bandwidth_value":"100.00","bandwidth_unit":"M"} 

我想要;

{"id": 10,"max_devices":5,"bandwidth":{"value":"100.00","unit":"M"}} 

我該怎麼辦?

+0

http://stackoverflow.com/questions/26218141/nesting-fields-in-serialization-with-django-的重複休息框架。 – brawaga

+0

有一個答案。 http://stackoverflow.com/questions/28187476/django-rest-framework-how-to-nest-several-fields-in-a- serializer。 – brawaga

回答

2

您可以使用自定義的模型序列象下面爲您Offer型號:

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}}