Django Rest框架组字段在一起

时间:2016-04-23 15:57:36

标签: python django rest django-rest-framework

我有一个Django模型Offer,其字段名称为...以及bandwidth_value和bandwidth_unit。我使用Django REST框架类ModelSerializer来序列化我的模型。 我有:

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

我想拥有;

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

我该怎么办?

1 个答案:

答案 0 :(得分: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}}