我不知道我是否针对我的问题找到了正确的问题。
在我的查询中,我想动态更改注释名称的名称取决于其危险程度。但我似乎无法得到它。它只返回名称本身,即" hazard_level"。
这一行问题.annotate(hazard_level=Count('brgy_locat')))
。如何获取这些危险等级,然后将其用作注释查询的名称。所以JSON将是这样的:
[
{
"Low": 2,
"brgy_locat": "Barangay 9",
"municipali": "Cabadbaran City"
},
{
"High": 5,
"brgy_locat": "Comagascas",
"municipali": "Cabadbaran City"
}
...
]
这是我的代码:
if request.method == "GET":
# create a list
to_json = []
# this code is results a messy JSON data that need underscore.js to manipulate
# in order for us to use datatables
hazard_levels = ['High', 'Medium', 'Low']
for hazard_level in hazard_levels:
reference = FloodHazard.objects.filter(hazard=hazard_level)
ids = reference.values_list('id', flat=True)
for myid in ids:
getgeom = FloodHazard.objects.get(id=myid).geom
response = list( PolyStructures
.objects
.filter(geom__within=getgeom)
.values('brgy_locat', 'municipali')
.annotate(hazard_level=Count('brgy_locat'))
)
to_json.append(response)
return HttpResponse(list(json.dumps(to_json)),
content_type='application/json')
答案 0 :(得分:0)
这是一种无代码方法:
response = list( PolyStructures
.objects
.filter(geom__within=getgeom)
.values('brgy_locat', 'municipali')
.annotate(hazard_level=Count('brgy_locat'))
)
response_cooked = [ { ( "high" if x.hazard_level >= 5
else "low"
) : x.hazard_level,
"brgy_locat": x."brgy_locat",
"municipali": x.municipali
}
for x in response
]
to_json.append(response_cooked)