Reputation: 55
I am fairly new to json and javascript and I've been trying to pass django queryset to a js array.
I've managed to pass the .values queryset to javascript through json.
Django to JSON code
def getPorts(request):
ports = Port.objects.all()
data = serializers.serialize('json', ports, fields=('name'))
return JsonResponse(data, safe=False)
JS where I am currently stuck at
$.ajax({
url: 'getPorts,
dataType: 'json',
success: function(result){
var ports = JSON.parse(result)
console.log(ports[0]);
}
});
ports[0] gives me something like {model: "Coordinator.port", pk: 1, fields: {…}} fields: {name: "Fa0/1"} model:"Coordinator.port" pk:1 proto:Object
Is there a way to extract only the 'name' attribute? I've been trying to treat it like a 2d array but I haven't really been successful
Upvotes: 1
Views: 1612
Reputation: 600059
ports[0]['fields']['name']
If you want more control over the serialization format, you should look at django-rest-framework.
Upvotes: 3