0

This code seems to work fine when I used Django console and just print it.

reference = FloodHazard.objects.filter(hazard='High')
ids = reference.values_list('id', flat=True)

for myid in ids:
    getgeom = FloodHazard.objects.get(id=myid).geom
    response = BuildingStructure.objects.filter(geom__intersects=getgeom).values(
        'brgy_locat').annotate(counthigh=Count('brgy_locat'))
    print response

I was able to show all the values, but when using HttpResponse, it returns an empty set. What is the proper way of returning JSON data from a queryset? So far, tried this:

reference = FloodHazard.objects.filter(hazard='High')
ids = reference.values_list('id', flat=True)
response = {}
for myid in ids:
    getgeom = FloodHazard.objects.get(id=myid).geom
    response['high'] = BuildingStructure.objects.filter(geom__intersects=getgeom).values(
        'brgy_locat').annotate(counthigh=Count('brgy_locat'))

json_post = ujson.dumps(list(response))
return HttpResponse(json_post, content_type='application/json')

1 Answer 1

1

There is no much sense in your code. You assign all querysets to the single key in the response dict. You should use a list for this purpose:

As far as I understand the code should be something like this:

response = []
for myid in ids:
    getgeom = FloodHazard.objects.get(id=myid).geom
    response.extend(BuildingStructure.objects.filter(geom__intersects=getgeom)
                                     .values('brgy_locat')
                                     .annotate(counthigh=Count('brgy_locat')))

json_post = ujson.dumps(response)

If you want to return a hazard level as well as the list of buildings then you can return a dict:

json_post = ujson.dumps({'hazard': 'high', 'buildings': response})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.