对来自 DJango QuerySet 的 JSON 数据进行分组

Grouping JSON data from DJango QuerySet

我从我的 Django QuerySet:

得到了这个结果 (JSON)
{
    "high": [{
        "counthigh": 27,
        "brgy_locat": "Barangay 6"
    }, {
        "counthigh": 3,
        "brgy_locat": "Mabini"
    }],
    "medium": [{
        "brgy_locat": "Barangay 6",
        "countmedium": 31
    }, {
        "brgy_locat": "Tolosa",
        "countmedium": 9
    }],
    "low": [{
        "brgy_locat": "Barangay 12",
        "countlow": 29
    }, {
        "brgy_locat": "Mabini",
        "countlow": 25
    }, {
        "brgy_locat": "Barangay 9",
        "countlow": 35
    }]
}

我想按 brgy_locat 及其值进行分组:

brgy_locat | countlow | countmedium | counthigh

主要是因为,我正在使用数据表。

顺便说一句,这是我的 views.py:

response_data = {} 
response_data["medium"] = list(BuildingStructure.objects.filter(geom__intersects=getgeom_medium).values( 'brgy_locat').annotate(countmedium=Count('brgy_locat'))) 
response_data["high"] = list(BuildingStructure.objects.filter(geom__intersects=getgeom).values('brgy_locat').annotate( counthigh=Count('brgy_locat'))) 
response_data["low"] = list(BuildingStructure.objects.filter(geom__intersects=getgeom_low).values('brgy_locat').annotate( countlow=Count('brgy_locat'))) 
return HttpResponse(json.dumps(response_data), content_type='application/json')

您不能在 QuerySet 中执行您要查找的操作。您需要在 python 中操作您的数据。这是一种方法。它假定每个元素都不会有冲突的键。意思是 highmediumlow 的字典中只有 counthigh 等键。当然还有brgy_locat

data = {
    "high": [{
        "counthigh": 27,
        "brgy_locat": "Barangay 6"
    }, {
        "counthigh": 3,
        "brgy_locat": "Mabini"
    }],
    "medium": [{
        "brgy_locat": "Barangay 6",
        "countmedium": 31
    }, {
        "brgy_locat": "Tolosa",
        "countmedium": 9
    }],
    "low": [{
        "brgy_locat": "Barangay 12",
        "countlow": 29
    }, {
        "brgy_locat": "Mabini",
        "countlow": 25
    }, {
        "brgy_locat": "Barangay 9",
        "countlow": 35
    }]
}

result = {}

for category in data.values():
    for element in category:
        key = element.pop('brgy_locat')
        if key not in result:
            result[key] = {}
        result[key].update(element)

那么结果应该是:

{
    "Barangay 6": {
        "counthigh": 27,
        "countmedium": 31
    }, 
    "Mabini": {
        "counthigh": 3,
        "countlow": 25
    },
    "Tolosa": {
        "countmedium": 9
    },
    "Barangay 12":{
        "countlow": 29
    },
    "Barangay 9": {
        "countlow": 35
    }
}