Gian Diaz
Gian Diaz

Reputation: 55

How to return a django queryset in ajax httpresponse

I've been trying to retrieve a Django queryset and store it in a Javascript variable through Ajax.

I'm currently trying to use the code below but I keep on receiving the "Queryset is not JSON Serializable. I'm quite new to both django and json formats. How do I workaround this?

html/javascript page

$.ajax({url: "http://127.0.0.1:8000/getPorts,
    success: function(result){
        var res = JSON.parse(result);
    }
});

views.py

def getPorts(request):
    JSONer = {} 
    ports = Port.objects.all()

    JSONer['ports'] = ports

    return HttpResponse(json.dumps(JSONer))

Also, if anyone would like to suggest a better way to use ajax to send/retrieve data to/from views, I am open to advice. Thank you

Upvotes: 2

Views: 4593

Answers (3)

rajkris
rajkris

Reputation: 1793

Maybe try serializing the queryset before sending it back to the ajax like this:

from django.core import serializers
data = serializers.serialize('json', list(ports))

You can specify the required fields as shown above.

Upvotes: 2

priyankvex
priyankvex

Reputation: 6040

Short Answer: You don't

Please understand, querysets are not actual serializable data. They just help in querying that data from the database.

And as others have pointed, just convert them to a json response either by using JsonResponse or manually dumping into as json and sending it in the HttpResponse.

Upvotes: 0

Vitor Freitas
Vitor Freitas

Reputation: 3610

You can also use the built-in JsonResponse, that way you don't have to call json.dumps() and it will also set the proper headers.

First your JavaScript code:

$.ajax({
  url: '/getPorts',
  dataType: 'json',
  sucess: function (result) {
    console.log(result.ports);
  }
});

By setting the dataType you already get a parsed object. Also, you don't need to hardcore the absolute url in the url parameter.

Then, in your view:

from django.http import JsonResponse

def getPorts(request):
    JSONer = {} 
    ports = Port.objects.values()
    JSONer['ports'] = ports
    return JsonResponse(JSONer)

Upvotes: 1

Related Questions