1

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

1 Answer 1

3
ports[0]['fields']['name']

If you want more control over the serialization format, you should look at django-rest-framework.

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.