Django - 如何将json反序列化为嵌套对象

时间:2017-05-29 11:11:12

标签: python django serialization django-rest-framework deserialization

我有以下问题。我需要使用json中的POST数据创建一个复杂的对象。在models.py文件中,我有一个名为“Company”的主对象:

class Company(models.Model):
    name = models.CharField(max_length=255)
    descr = models.CharField(max_length=255)

    def __str__(self):
        return self.name

然后我有“建筑”:

class Building(models.Model):
    name = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    location = models.TextField()
    company= models.ForeignKey("Company", related_name="buildings", on_delete=models.CASCADE)

等其他几个班级(即“楼层”,“区域”,“房间”)。

我从POST请求获得的json是:

    {
    "id": 1,
    "buildings": [{
        "id": 3,
        "floors": [{
            "id": 1,
            "floor": -1,
            "descr": "underground",
            "building": 3
        }],
        "areas": [{
            "id": 1,
            "rooms": [{
                "id": 1,
                "floor": 1,
                "area": 1,
                "descr": "First Room"
            }],
            "descr": "Dev area",
            "building": {
                "id": 3,
                "name": "Sede",
                "city": "Rome",
                "location": "mylocation",
                "company": {
                    "id": 1,
                    "name": "Test",
                    "descr": "Test"
                }
            }
        }],
        "name": "Sede",
        "city": "Rome",
        "location": "mylocation",
        "company": 1
    }],
    "name": "Test",
    "descr": "Test"
}

当我尝试从json创建一个“Company”对象时,它只会创建以下内容:

{
    "id": 1,
    "buildings": [],
    "name": "Test",
    "descr": "Test"
}

而不是完整的结构。

我的序列化器如下:

class BuildingSerializer(serializers.ModelSerializer):
    floors= FloorSerializer(read_only=True, many=True)
    areas = AreaSerializer(read_only=True, many=True)
    class Meta:
        model = Building
        fields = '__all__'
        read_only_fields = ('id',)

class CompanySerializer(serializers.ModelSerializer):
    buildings= BuildingSerializer(read_only=True, many=True)
    class Meta:
        model = Company
        fields = '__all__'
        read_only_fields = ('id',)

我该如何解决这个问题?

P.S。我知道json有点多余!

2 个答案:

答案 0 :(得分:0)

99%的时间没有获得嵌套数据是因为您正在发送带有表单内容类型的JSON有效内容。

通过将Content-Type标头设置为application/json,在您的客户端明确指出您要发送JSON,这应该可以解决内容问题。

答案 1 :(得分:0)

您将建筑物指定为只读字段:http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields

尝试在序列化程序中删除该参数:

class BuildingSerializer(serializers.ModelSerializer):
    floors= FloorSerializer(many=True)
    aree = AreaSerializer(many=True)
    class Meta:
        model = Building
        fields = '__all__'
        read_only_fields = ('id',)

class CompanySerializer(serializers.ModelSerializer):
    buildings= BuildingSerializer(many=True)
    class Meta:
        model = Company
        fields = '__all__'
        read_only_fields = ('id',)