[Fixed]-More efficient way of writing this function? (Django, AJAX)

1👍

You can reduce the entire if statement section by creating a dictionary lookup with a tuple as values

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')

You also seem to be trying to serialize models, something which Django Rest Framework specializes in, so just using that instead would stop the requirement for you to manually do all this in a view.

👤Sayse

Leave a comment