使用此查询:
def high_hazard(request):
reference_high = FloodHazard.objects.filter(hazard='High')
ids_high = reference_high.values_list('id', flat=True)
flood_hazard = []
djf = Django.Django(geodjango='geom', properties=['bldg_name', 'bldg_type'])
geoj = GeoJSON.GeoJSON()
for myid in ids_high:
getgeom = FloodHazard.objects.get(id=myid).geom
response_high = BuildingStructure.objects.filter(geom__intersects=getgeom)
get_hazard = geoj.encode(djf.decode(response_high.transform(900913)))
flood_hazard.append(get_hazard)
return HttpResponse(flood_hazard, content_type='application/json')
我能够根据BuildingStructure
类型过滤FloodHazard
模型,在这种情况下使用" high"值。虽然它返回一个JSON数据,但输出却搞砸了。我猜是因为它在循环期间测试FloodHazard
模型中的所有几何。因此,它返回几个空集或空和许多FeatureCollection,这使得它成为无效的JSON数据。上面的查询输出如下:
{
"crs": null,
"type": "FeatureCollection",
"features": [
]
}{
"crs": null,
"type": "FeatureCollection",
"features": [
]
}{
"crs": null,
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "MultiPoint",
"coordinates": [
[
13974390.863509608,
1020340.6129766875
]
]
},
"type": "Feature",
"id": 3350,
"properties": {
"bldg_name": "",
"bldg_type": ""
}
},
{
"geometry": {
"type": "MultiPoint",
"coordinates": [
[
13974400.312472697,
1020356.5477410051
]
]
},
"type": "Feature",
"id": 3351,
"properties": {
"bldg_name": "",
"bldg_type": ""
}
}
]
}
当我用JSON验证器测试它时,它是无效的。那么,有没有办法重构(使用underscore.js或jquery)这个JSON输出如下?或者我需要更改我的查询?
{
"crs": null,
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "MultiPoint",
"coordinates": [
[
13974390.863509608,
1020340.6129766875
]
]
},
"type": "Feature",
"id": 3350,
"properties": {
"bldg_name": "",
"bldg_type": ""
}
},
{
"geometry": {
"type": "MultiPoint",
"coordinates": [
[
13974400.312472697,
1020356.5477410051
]
]
},
"type": "Feature",
"id": 3351,
"properties": {
"bldg_name": "",
"bldg_type": ""
}
}
]
}
并忽略/删除所有没有值的FeatureCollection,并将所有值分组。 Here是上述查询的结果,仅供参考。
答案 0 :(得分:1)
而不是
return HttpResponse(flood_hazard, content_type='application/json')
尝试
return HttpResponse(json.dumps(flood_hazard), content_type='application/json')
您必须在顶部import json
。