Edgar Navasardyan Edgar Navasardyan - 6 months ago 19
JSON Question

Django - json response allowing for json[i][j] reference rather than json[0].field.field_name

I have Django view returning JSON to JS.

def some_view(request, param):
my_queryset = SomeModel.objects.filter(...).select_related('related_model')
serialized_data = serializers.serialize( "json", [x.some_related_field for x in my_queryset])
return HttpResponse(serialized_data, content_type='application/json')


Now, to get the value of some_related_field, I have to write in JS:

obj[i].fields.some_related_field[j]


My goal is to return the json from python in a way which should allow for obj[i][j] syntax. Is it possible ?

I expect I have to use dump method, but it is absolutely important that I grab the fields of a related model as well. Up to now, I've failed to grab related fields with the dump method.

Answer

The serialized output format depends on the serializer you're using.

If you're running Django 1.7+, you can return a JsonResponse (with safe=False) instead of a HttpResponse. Note, you'll need to specify safe=False if you want to return a JSON list at the root level

e.g.

def some_view(request, param):
    my_queryset = SomeModel.objects.filter(...).select_related(...)
    list_data = [x.some_related_field for x in my_queryset]
    return JsonResponse(list_data, safe=False)

Otherwise, if you're using a version of Django less than 1.7, you could do:

import json

def some_view(request, param):
    my_queryset = SomeModel.objects.filter(...).select_related(...)
    list_data = [x.some_related_field for x in my_queryset]
    return HttpResponse(json.dumps(list_data), content_type='application/json')