在Django中附加dict列表

时间:2015-03-20 07:58:02

标签: python django

我有这个问题:

for myid in ids_high:
    getgeom = FloodHazard.objects.get(id=myid).geom
    response_high = list(BuildingStructure.objects.filter(geom__intersects=getgeom).values(
        'brgy_locat','bldg_type','bldg_name').annotate(counthigh=Count('brgy_locat')))          
    to_json.append(response_high)

结果如下:

[
    {
        "counthigh": 1,
        "brgy_locat": "Tolosa",
        "bldg_name": "",
        "bldg_type": ""
    },
    {
        "counthigh": 7,
        "brgy_locat": "Barangay 9",
        "bldg_name": "",
        "bldg_type": ""
    },
    {
        "counthigh": 3,
        "brgy_locat": "Mabini",
        "bldg_name": "",
        "bldg_type": ""
    }
]

to_json是一个列表,我想要一个dict,例如["类型":"高&#34]。怎么样?到目前为止,我尝试了追加和范围。如何追加两次?有可能吗?

预期输出是这样的:

{
        "counthigh": 3,
        "brgy_locat": "Mabini",
        "bldg_name": "",
        "bldg_type": "",
        "type":"high"
}

依旧......

1 个答案:

答案 0 :(得分:1)

您应该能够遍历response_high并将密钥type添加到每个条目。

for myid in ids_high:
    getgeom = FloodHazard.objects.get(id=myid).geom
    response_high = list(BuildingStructure.objects.filter(geom__intersects=getgeom).values(
        'brgy_locat','bldg_type','bldg_name').annotate(counthigh=Count('brgy_locat')))          
    for entry in response_high:
         entry['type'] = 'high'
    to_json.append(response_high)