我编写函数的方式现在有效,我只是想知道是否有更好或更有效的方法来编写它。这是一个ajax调用,它获取了一个列表,用于进一步过滤地理位置,例如,如果选择了县,那么它将获得该州所有县的列表。 我还在学习编码,并希望在使用良好的编码实践方面做得更好。
$.ajax({
url : "filters",
type : "POST",
data : { search : selected_state, geog : selected_geog },
success: function(data) {
$.each(data, function(i, v) {
switch(selected_geog) {
case 'County':
case 'Dma':
filters.push(v.fields.name);
break;
case 'Zip':
var exists = $.inArray(v.fields.zcta, data_check);
if (exists < 0) {
data_check.push(v.fields.zcta);
}
data_check.sort();
var exists2 = $.inArray(v.fields.county, filters);
if (exists2 < 0) {
filters.push(v.fields.county);
}
filters.sort();
break;
case 'CD':
filters.push(v.fields.cd114fp);
break;
case 'Zones':
var exists = $.inArray(v.fields.p_dma, filters);
if (exists < 0) {
filters.push(v.fields.p_dma);
}
filters.sort();
var exists2 = $.inArray(v.fields.owner, attrfilters);
if (exists2 < 0) {
attrfilters.push(v.fields.owner);
}
SHPconverter.attrfilters.sort();
var exists3 = $.inArray(v.fields.scode, data_check);
if (exists3 < 0) {
data_check.push(v.fields.scode);
}
data_check.sort();
break;
}
})
}
})
这是django视图
def filters(request):
searchVar = request.POST.getlist('search[]')
geogVar = request.POST.get('geog')
if geogVar == 'County':
county_as_json = serialize(
'json', County.objects.filter(
state__in=searchVar).order_by('state', 'name'))
return HttpResponse(county_as_json, content_type='json')
elif geogVar == 'DMA':
dma_as_json = serialize(
'json', Dma.objects.filter(
state__in=searchVar).order_by('state', 'name'))
return HttpResponse(dma_as_json, content_type='json')
elif geogVar == 'CD':
cd_as_json = serialize(
'json', Cd.objects.filter(
state__in=searchVar).order_by('state', 'cd'))
return HttpResponse(cd_as_json, content_type='json')
elif geogVar == 'Zip':
zip_as_json = serialize(
'json', Zip.objects.filter(
state__in=searchVar).order_by('state', 'county'))
return HttpResponse(zip_as_json, content_type='json')
elif geogVar == 'Zones':
zones_as_json = serialize(
'json', Zones.objects.filter(
state__in=searchVar).order_by('sname'))
return HttpResponse(softzones_as_json, content_type='json')
答案 0 :(得分:1)
您可以通过使用元组作为值
创建字典查找来减少整个if语句部分geo_lookup = {'County': (County, ['state', 'name']),
'DMA': (Dma, ['state', 'name']),
'CD': (Cd, ['state', 'cd']),
'Zip': (Zip, ['state', 'county']),
'Zones': (Zones, ['sname']),
}
lookup_model = geo_lookup[geogVar][0]
ordering = geo_lookup[geogVar][1]
as_json = serialize('json', lookup_model.objects.filter(state__in=searchVar).order_by(*ordering))
return HttpResponse(as_json, content_type='json')
你似乎也试图序列化模型,这是Django Rest Framework专门研究的,所以只需使用它就可以阻止你在视图中手动完成所有这些操作。