In ASP.NET MVC or ASP.NET Web Api, I can receive data list in jQuery or Angular.js if my C# code like below:
return Json(list, JsonRequestBehavior.AllowGet);
I'm newbie to Django so I don't know how to write in backend if I want to receive the list in my front page.
jQuery:
$.getJSON(url, function (list) {
result=list
};
or
Angular.js:
$http.get(url).success(function(list) {
result=list
};
My Model
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
Assume that there are two polls in database,
I have tried 3 situations in views.py.
list = Poll.objects.all()
1.return HttpResponse(list)
What I get in jQuery callback or Angular callback will be "Poll objectPoll object".
2.return HttpResponse(list.values())
I will get SyntaxError: " Unexpected token ' "
3.return HttpResponse(list.values_list())
I will get a string(it also seems not in json):
"(1, u'Which city is the most beautiful all over the world?', datetime.datetime(2013, 10, 19, 7, 8, tzinfo=<UTC>))(2, u'What is your favourite city?', datetime.datetime(2013, 10, 19, 7, 8, 43, tzinfo=<UTC>))"
But In ASP.NET MVC or ASP.NET Web Api, even I return json list in backend(C#), I always get deserialized list in my js callback, so I can use it directly.
Did I use wrong APIs of QuerySet or wrong List Type?
Thanks in advance.
Edit to add info when I tried some answers:
Thanks for the detail answer, but I get "datetime.datetime(2013, 10, 19, 7, 8, tzinfo=) is not JSON serializable" if I use:
return HttpResponse(json.dumps([poll.dict for poll in Poll.objects.all() ]))
Then I change my code to
return HttpResponse(json.dumps(Poll.objects.values(), cls=DjangoJSONEncoder))
but what I get is "[{'pub_date': datetime.datetime(2013, 10, 19, 7, 8, tzinfo=), 'question': u'Which city is the most beautiful all over the world?', u'id': 1}, {'pub_date': datetime.datetime(2013, 10, 19, 7, 8, 43, tzinfo=), 'question': u'What is your favourite city?', u'id': 2}] is not JSON serializable".
After googled, I change my code to
return HttpResponse(serializers.serialize('json', Poll.objects.all()))
This time is no error in js callback, but the received data structure liked below:
Array[2]
0: Object
fileds: Object
pub_date:...
question:...
model: "polls.poll"
pk: 1
1: Object
fileds: Object
pub_date:...
question:...
model: "polls.poll"
pk: 2
What should I do if I want to get:
Array[2]
0: Object
id: 1
question:...
pub_date:...
1: Object
id: 2
question:...
pub_date:...