【问题标题】:Grouping JSON data from DJango QuerySet对来自 DJango QuerySet 的 JSON 数据进行分组
【发布时间】:2015-03-04 01:40:02
【问题描述】:

我的 Django QuerySet 有这个结果(JSON):

{
    "high": [{
        "counthigh": 27,
        "brgy_locat": "Barangay 6"
    }, {
        "counthigh": 3,
        "brgy_locat": "Mabini"
    }],
    "medium": [{
        "brgy_locat": "Barangay 6",
        "countmedium": 31
    }, {
        "brgy_locat": "Tolosa",
        "countmedium": 9
    }],
    "low": [{
        "brgy_locat": "Barangay 12",
        "countlow": 29
    }, {
        "brgy_locat": "Mabini",
        "countlow": 25
    }, {
        "brgy_locat": "Barangay 9",
        "countlow": 35
    }]
}

我想按 brgy_locat 及其值对其进行分组:

brgy_locat | countlow | countmedium | counthigh

主要是因为,我使用的是数据表。

顺便说一句,这是我的观点.py:

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'))) 
return HttpResponse(json.dumps(response_data), content_type='application/json')

【问题讨论】:

  • 如何从 QuerySet 中获取 JSON?你用的是什么数据库?
  • 来自 HttpResponse,我正在使用 PostgreSQL

标签: json django jquery-datatables


【解决方案1】:

您无法在 QuerySet 中执行您要查找的内容。您需要在 python 中操作数据。这是一种方法。它假定每个元素不会有冲突的键。意思是highmediumlow 的字典中只有counthigh 等键。当然除了brgy_locat

data = {
    "high": [{
        "counthigh": 27,
        "brgy_locat": "Barangay 6"
    }, {
        "counthigh": 3,
        "brgy_locat": "Mabini"
    }],
    "medium": [{
        "brgy_locat": "Barangay 6",
        "countmedium": 31
    }, {
        "brgy_locat": "Tolosa",
        "countmedium": 9
    }],
    "low": [{
        "brgy_locat": "Barangay 12",
        "countlow": 29
    }, {
        "brgy_locat": "Mabini",
        "countlow": 25
    }, {
        "brgy_locat": "Barangay 9",
        "countlow": 35
    }]
}

result = {}

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

那么结果应该是:

{
    "Barangay 6": {
        "counthigh": 27,
        "countmedium": 31
    }, 
    "Mabini": {
        "counthigh": 3,
        "countlow": 25
    },
    "Tolosa": {
        "countmedium": 9
    },
    "Barangay 12":{
        "countlow": 29
    },
    "Barangay 9": {
        "countlow": 35
    }
}

【讨论】:

  • 你在上面运行同样的循环逻辑。
  • 有点帮助,我如何在我的 JS 中访问它们?
  • 您应该为该问题创建一个新问题。它与这个无关,您需要提供有关您的用例的更多详细信息。
  • 您是否介意更新答案以便输出例如{0: brgy_locat:"Tolosa",countlow:9,countmedium:7,counthigh:8}
猜你喜欢
  • 1970-01-01
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多