1👍
✅
You can’t do what you’re looking for within a QuerySet. You’ll need to manipulate your data in python. Here’s one way to do it. It assumes that each element won’t have conflicting keys. Meaning high
, medium
, low
‘s dictionaries will only have the counthigh
, etc key in them. Besides brgy_locat
of course.
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)
Then result should be:
{
"Barangay 6": {
"counthigh": 27,
"countmedium": 31
},
"Mabini": {
"counthigh": 3,
"countlow": 25
},
"Tolosa": {
"countmedium": 9
},
"Barangay 12":{
"countlow": 29
},
"Barangay 9": {
"countlow": 35
}
}
Source:stackexchange.com