通过DRF展平json返回

时间:2018-11-30 03:28:15

标签: django django-rest-framework

我以以下格式返回了json API。
但是我想返回如下分解命名区域密钥的json API。
谁能告诉我如何修改序列化程序来实现这一目标?
还在下面指定了serializer.py。
有关models.py和views.py,请参阅my previous post

当前

{
    "zone": {
        "zone": "office_enclosed",
        "namingzone": [
            {
                "naming": "moffice"
            }
        ]
    },
    "lpd": 11.9,
    "sensor": true
},
{
    "zone": {
        "zone": "office_open",
        "namingzone": [
            {
                "naming": "off"
            },
            {
                "naming": "office"
            }
        ]
    },
    "lpd": 10.5,
    "sensor": true
}  

目标

{
    "zone": "office_enclosed",
    "naming": "moffice",
    "lpd": 11.9,
    "sensor": true
},
{
    "zone": "office_open",
    "naming": "off",
    "lpd": 10.5,
    "sensor": true
},
{
    "zone": "office_open",
    "naming": "office",
    "lpd": 10.5,
    "sensor": true
}  

serializer.py

class namingNewSerializer(serializers.ModelSerializer):

    class Meta:
        model=Naming
        fields=('naming',)

class zoneSerializer(serializers.ModelSerializer):
    namingzone=namingNewSerializer(many=True)

    class Meta:
        model=Zone
        fields = ('zone','namingzone')

class lightSerializer(serializers.ModelSerializer):
    zone = zoneSerializer()

    class Meta:
        model=Light
        fields = ('zone','lpd','sensor')

class namingSerializer(serializers.ModelSerializer):
    zone=zoneSerializer()

    class Meta:
        model=Naming
        fields=('zone','naming')

1 个答案:

答案 0 :(得分:0)

请参阅有关source的DRF字段文档。它将为您提供帮助。

https://www.django-rest-framework.org/api-guide/fields/#source