我不知道我是否针对我的问题提出了正确的问题。
在我的查询中,我希望根据其危险级别动态更改注释名称的名称。但我似乎不能理解。它只返回名称本身,即"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')发布于 2015-04-27 14:42:08
这是一种无代码的方法:
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) https://stackoverflow.com/questions/29885827
复制相似问题