如何更改此QuerySet以获得此JSON数据输出

时间:2015-03-04 05:06:00

标签: python json django

从我目前的查询:

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')))

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

return HttpResponse(json.dumps(result), content_type = 'application/json')

JSON输出是这样的:

{
    "Mabini": {
        "counthigh": 3,
        "loc": "Mabini",
        "countmedium": 2,
        "countlow": 25
    },
    "Barangay 12": {
        "loc": "Barangay 12",
        "countlow": 29
    },
    "Katugasan": {
        "loc": "Katugasan",
        "countlow": 3
    }
}

但我想改为输出:

{
    "0": {
        "counthigh": 3,
        "loc": "Mabini",
        "countmedium": 2,
        "countlow": 25
    },
    "1": {
        "loc": "Barangay 12",
        "countlow": 29
    },
    "2": {
        "loc": "Katugasan",
        "countlow": 3
    }
}

我是Django和Python的新手,我尝试循环并使用变量作为索引,但输出发生了变化,我无法弄明白。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

添加另一个简单的结果转换:

json_result = {str(i): v for i, v in enumerate(result.values())}
return HttpResponse(json.dumps(json_result), content_type='application/json')

更新:无法保证dict中键的顺序。但是如果你想获得JSON的确切输出,那么你可以使用python 2.7的collections.OrderedDict

from collections import OrderedDict
json_result = OrderedDict((str(i), v) for i, v in enumerate(result.values()))

答案 1 :(得分:0)

您的输出正在更改,因为您使用字典存储密钥。字典不保持其元素的顺序(它们是无序的),当你想要保持元素的顺序时,它更适合你使用python列表。

E.g。

results = []
#...
results.append(...)