Django查询集-查找两个查询集之间的百分比

时间:2020-04-28 08:16:44

标签: python django django-views django-queryset

我有两个查询集-

>>> region_carrier_groupby_total =
<QuerySet [{'region_carrier': 'tc2 - rc2', 'DID_Count': 2}, {'region_carrier': 'tc1 - rc1', 'DID_Count': 16}]>


>>> region_carrier_groupby_available =
<QuerySet [{'region_carrier': 'tc2 - rc2', 'DID_Count': 1}, {'region_carrier': 'tc1 - rc1', 'DID_Count': 14}]>

此处的目的是找到按region_carrier分组的DID计数的可用百分比。 例如-

region_carrier:tc1-rc1,百分比DID_Count =(14/16)* 100 region_carrier:tc2-rc2,百分比DID_Count =(1/2)* 100

1 个答案:

答案 0 :(得分:1)

所以我想您想用不在sql中的代码来完成它:

total_counter = {}
for item in region_carrier_groupby_total:
    total_counter[item['region_carrier']] = item['DID_Count']

total_available = {}
for item in region_carrier_groupby_available:
    total_available[item['region_carrier']] = item['DID_Count']

result = {}
for key, total in total_counter.items():
    result[key] = total_available.get(key, 0) / total