Python 在Django中传递多值\u列表
我在views.py中有以下代码:Python 在Django中传递多值\u列表,python,json,django,Python,Json,Django,我在views.py中有以下代码: def pins_info(request): if request.method == "GET": getpin = request.GET.get('pin', None) m = ButuanMaps.objects.filter(clandpin=getpin). values_list('landproperty__ctaxdec') n = ButuanMaps.ob
def pins_info(request):
if request.method == "GET":
getpin = request.GET.get('pin', None)
m = ButuanMaps.objects.filter(clandpin=getpin).
values_list('landproperty__ctaxdec')
n = ButuanMaps.objects.filter(clandpin=getpin).
values_list('ssectionid__sbrgyid__cbrgyname')
return HttpResponse(json.dumps({'taxdec': list(m),'brgy': list(n)}),
content_type='application/json')
我工作得很好,但当我想要得到其他值时,它并没有那么有效。我可以在我的模板中访问结果,如下所示:
success: function(data) {
taxdec = data['taxdec'];
brgy = data['brgy'];
var inputform = $('#forminput').val();
if( inputform == "Select Land PIN") {
alert('Please Select Land PIN')
}
else{
$('#status').append(
"<p>Tax Declaration: " + taxdec + "<br/>Barangay: " + brgy + "</p>"
);
}
}
但是我如何将其传递到我的模板?如果我们将您的
m
和n
查询视为:
m = range(5)
n = range(6, 11)
然后查询m=butuanmap.objects.filter(clandpin=getpin)。值列表('landproperty'uuuu ctaxdec','ssectionid\uuuu sbrgyid\uuu cbrgyname')
相当于以下结构:
new = zip(m, n)
#[(0, 6), (1, 7), (2, 8), (3, 9), (4, 10)]
所以你可以“转置”它:
然后根据该命令和您的密钥构建一个dict
:
results = dict(zip(['taxdec', 'brgy'], zip(*new))))
# {'brgy': (6, 7, 8, 9, 10), 'taxdec': (0, 1, 2, 3, 4)}
然后json.dump
结果
或者对JSON名称和列名值使用
OrderedDict
,并进一步概括:
from collections import OrderedDict
keyvals = OrderedDict([
('taxdec','landproperty__ctaxdec'),
('brgy', 'ssectionid__sbrgyid__cbrgyname')
])
m = ButuanMaps.objects.filter(clandpin=getpin).values_list(*keyvals.values())
result = dict(zip(keyvals, zip(*m)))
这样,您就可以在同一查询的同一位置添加/删除要选择的列及其关联的JSON值。谢谢!我使用了
orderedict
然后json.dumps
结果。类似这样:返回HttpResponse(json.dumps(result),content\u type='application/json')
results = dict(zip(['taxdec', 'brgy'], zip(*new))))
# {'brgy': (6, 7, 8, 9, 10), 'taxdec': (0, 1, 2, 3, 4)}
from collections import OrderedDict
keyvals = OrderedDict([
('taxdec','landproperty__ctaxdec'),
('brgy', 'ssectionid__sbrgyid__cbrgyname')
])
m = ButuanMaps.objects.filter(clandpin=getpin).values_list(*keyvals.values())
result = dict(zip(keyvals, zip(*m)))