Django - 如何将json反序列化为嵌套对象
问题描述:
我遇到以下问题。我需要使用在json中发布的数据创建一个复杂的对象。在models.py文件,我有一个名为“公司”的主要对象:Django - 如何将json反序列化为嵌套对象
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,我收到了“公司”的对象,它不仅创造了以下内容:
{
"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有点多余!
答
99%的时间,当你没有得到嵌套的数据是因为你发送一个JSON负载与表单内容类型。
通过将Content-Type标头设置为application/json
并在您的客户端中明确表明您要发送JSON,并且应该解决内容问题。
答
您指定的建筑物作为一个只读字段: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',)
我已经指定了'应用/ json'格式在*的Content-Type *头。 –