Serializing Objects and Passing Multiple JSON Data in Django

Below is just an example, just replace the necessary Models and Queries:


def pins_info(request):
 if request.method == "GET":
  getpin = request.GET.get('pin', None)
  keyvals = OrderedDict([
   ('taxdec', 'landproperty__ctaxdec'),
   ('brgy', 'ssectionid__sbrgyid__cbrgyname'),
   ('landarea', 'narea')
  ])
  keyvals1 = OrderedDict([
   ('mydescription', 'description')
  ])

  m = ButuanMaps.objects.filter(clandpin=getpin).values_list(*keyvals.values())
  reference = ButuanMaps.objects.get(clandpin=getpin).geom
  within = SoilType.objects.filter(geom__contains=reference).values_list(*keyvals1.values())
  within1 = ErosionMap.objects.filter(geom__contains=reference).values_list(*keyvals1.values())
  result = dict(zip(keyvals, zip(*m)))
  result1 = dict(zip(keyvals1, zip(*within)))
  result2 = dict(zip(keyvals1, zip(*within1)))
  data = json.dumps([result, result1, result2], cls=DjangoJSONEncoder)
  return HttpResponse(data, content_type='application/json')
and in your template:
success: function(data) {
    taxdec = data[0]['taxdec'];
    brgy = data[0]['brgy'];
    landarea = data[0]['landarea'];
    soiltype = data[1]['mydescription'];
    erosion = data[2]['mydescription'];
    var inputform = $('#forminput').val();
    $('#infotable').append(
        "<tr><td class=\"bold\">Tax Declaration </td><td>" + taxdec +
        "</td></tr>" + "<tr><td class=\"bold\">Barangay</td><td>" +
        brgy + "</td></tr>" +
        "<tr><td class=\"bold\">Area of Land</td><td>" + landarea +
        " m&sup2;</td></tr>" +
        "<tr><td class=\"bold\">Soil Type</td><td>" + soiltype +
        "</td></tr>" + "<tr><td class=\"bold\">Erosion Type</td><td>" +
        erosion + "</td></tr>");
}
In order to identify the index of the data, just look up the console:

PS: Add `from collections import OrderedDict`,and from django.core.serializers.json import DjangoJSONEncoder in your views.py

Comments

Popular posts from this blog

Auto-calculate your Splinterlands Assets/Income

Creating a Simple Button for Demo

Splinterlands: Water Deck for Beginners