将平面模型转换为结构模型

时间:2015-06-13 14:25:28

标签: django django-rest-framework

基本上,我希望能够转换像

这样的东西
{
    "name": "",
    "street_address": "",
    "city": ""
}

进入这个

{
    "name": "",
    "address" : {
        "street_address": "",
        "city": ""
    }
}

同时仍保留一个看起来像这样的模型

class ModelA(models.Model):
    name = models.CharField()
    street_address = models.CharField()
    city = models.CharField()

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

重写class ModelASerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = ('name', 'street_address', 'city') def to_representation(self, instance): x = super(ModelASerializer, self).to_representation(instance) desired_response = {} desired_response['name'] = x['name'] desired_response['address'] = {'street_address': x['street_address'], 'city': x['city']} return desired_response 方法以更改序列化。

func saveContext () {
    if let moc = self.managedObjectContext {
        if moc.hasChanges  {
            do {
                try moc.save()
            } catch {
                NSLog("Unresolved error \(error)")
                abort()
            }
        }
    }
}

答案 1 :(得分:0)

这是关于序列化程序。

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelA
        fields = ('street_address', 'city')

class ModelASerializer(serializers.ModelSerializer):
    address = AddressSerializer()
    class Meta:
        model = ModelA
        fields = ('name', 'address')

ModelASerializer然后会屈服;

{
    "name": "",
    "address": {
        "street_address": "",
        "city": ""
    }
}