2
\$\begingroup\$

My code below returns a JSON data based on user's input or query in my HTML page or template. However, I need to modify or do some tweaking with my JSON data in order for me to use it in my datatables plugin. I am using underscore.js to reconstruct the JSON data.

def brgy_info(request):
    if request.method == "GET":
        get_muni = request.GET.get('munisipyo',default='All')
        get_brgy_id = request.GET.get('brgy_id')
        get_bldg_type = request.GET.getlist('bldg_type[]', default='All')   

        reference_high = FloodHazard.objects.filter(hazard='High')
        reference_medium = FloodHazard.objects.filter(hazard='Medium')
        reference_low = FloodHazard.objects.filter(hazard='Low')

        #get all ids based on filter
        ids_high = reference_high.values_list('id', flat=True)
        ids_medium = reference_medium.values_list('id', flat=True)
        ids_low = reference_low.values_list('id', flat=True)

        # create a list
        to_json = []
        args = []

        if get_muni != 'All Municipalities':
            args.append(Q(municipali=get_muni))

        if get_brgy_id not in ["Select Barangay","All Barangay"]:
            args.append(Q(brgy_locat=get_brgy_id))

        if get_bldg_type != 'All':      
            args.append(Q(bldg_type__in=get_bldg_type))

        # this code is results a messy JSON data that need underscore.js to manipulate
        # in order for us to use datatables
        for myid in ids_high:
            getgeom = FloodHazard.objects.get(id=myid).geom
            response_high = list(PolyStructures.objects.filter(geom__within=getgeom, *args).values(
                'bldg_type','bldg_name').annotate(count=Count('bldg_name')))
            for entry in response_high:
                entry['type'] = 'High'
                to_json.append(response_high)


        for myid in ids_medium:
            getgeom = FloodHazard.objects.get(id=myid).geom
            response_medium = list(PolyStructures.objects.filter(geom__within=getgeom, *args).values(
                'bldg_type','bldg_name').annotate(count=Count('bldg_name')))
            for entry in response_medium:
                entry['type'] = 'Medium'
                to_json.append(response_medium)

        for myid in ids_low:
            getgeom = FloodHazard.objects.get(id=myid).geom
            response_low = list(PolyStructures.objects.filter(geom__within=getgeom, *args).values(
                'bldg_type','bldg_name').annotate(count=Count('bldg_name')))
            for entry in response_low:
                entry['type'] = 'Low'
                to_json.append(response_low)


        return HttpResponse(json.dumps(list(to_json)), content_type='application/json')

I find it very taskful for my page, without using underscore.js. This is the snippet of the JSON data result, which is just a sample based on this query:

http://127.0.0.1:8000/cnt_bldg/?brgy_id=Katugasan&munisipyo=Cabadbaran+City

[
    [
        {
            "count": 1,
            "type": "Low",
            "bldg_name": "",
            "bldg_type": ""
        }
    ],
    [
        {
            "count": 1,
            "type": "Low",
            "bldg_name": "Katugasan Multi-Purpose Gym",
            "bldg_type": "Sport Center/Gymnasium/Covered Court"
        },
        {
            "count": 16,
            "type": "Low",
            "bldg_name": "",
            "bldg_type": ""
        },
        {
            "count": 5,
            "type": "Low",
            "bldg_name": "Katugasan Elementary School",
            "bldg_type": "School"
        }
    ],
    [
        {
            "count": 1,
            "type": "Low",
            "bldg_name": "Katugasan Multi-Purpose Gym",
            "bldg_type": "Sport Center/Gymnasium/Covered Court"
        },
        {
            "count": 16,
            "type": "Low",
            "bldg_name": "",
            "bldg_type": ""
        },
        {
            "count": 5,
            "type": "Low",
            "bldg_name": "Katugasan Elementary School",
            "bldg_type": "School"
        }
    ],
    [
        {
            "count": 1,
            "type": "Low",
            "bldg_name": "Katugasan Multi-Purpose Gym",
            "bldg_type": "Sport Center/Gymnasium/Covered Court"
        },
        {
            "count": 16,
            "type": "Low",
            "bldg_name": "",
            "bldg_type": ""
        },
        {
            "count": 5,
            "type": "Low",
            "bldg_name": "Katugasan Elementary School",
            "bldg_type": "School"
        }
    ],
    [
        {
            "count": 3,
            "type": "Low",
            "bldg_name": "",
            "bldg_type": ""
        }
    ]
]

Some values were duplicated, so how do I remove the duplicates? Any ideas to simplify this code for optimization purposes?

\$\endgroup\$
  • 1
    \$\begingroup\$ Hi! Welcome to Code Review. Nice first post; keep it up! \$\endgroup\$ – TheCoffeeCup Apr 23 '15 at 3:18
1
\$\begingroup\$

You have a lot of repeated code which does not respect one of the main principle of software engineering : Don't Repeat Yourself (aka DRY).

I might be wrong but I have the feeling that the whole code about hazard being High/Medium/Low can be re-written :

    hazard_levels = ['High', 'Medium', 'Low']
    for hazard_level in hazard_levels:
        reference = FloodHazard.objects.filter(hazard=hazard_level)
        ids = reference.values_list('id', flat=True)
        for myid in ids:
            getgeom = FloodHazard.objects.get(id=myid).geom
            response = list(PolyStructures.objects.filter(geom__within=getgeom, *args).values(
                'bldg_type','bldg_name').annotate(count=Count('bldg_name')))
            for entry in response:
                entry['type'] = hazard_level
                to_json.append(response)

Your code does not do anything in the request method is not GET, is this normal ? Should it raise an exception ?

\$\endgroup\$
  • \$\begingroup\$ I will try that. Yes, you are right. I think it is much better if it raise an exception but I just use this function in my Ajax script. In which it returns a bunch of JSON data. \$\endgroup\$ – Sachi Tekina Apr 25 '15 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.