1

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:...

2 Answers 2

1

You would do it slightly different in Python/Django.

Now, for queryset, .values() has a different meaning. You can read about it here

Returns a ValuesQuerySet — a QuerySet subclass that returns dictionaries when used as an iterable, rather than model-instance objects.

To achieve what you are looking for, you need the json module that python provides.

In the model Poll:

class Poll(models.Model):
    #attributes
    def to_json(self):
        return {'field1': 'attribute1', ... } #if you want a subset of all the attributes

and in the views:

polls = Poll.objects.all()
return HttpResponse(json.dumps([poll.to_json() for poll in polls ]))

Now, if you want all the attributes, you can just do:

polls = Poll.objects.all()
return HttpResponse(json.dumps([poll.__dict__ for poll in polls ]))

Also, do not use list as a local variable name, as it conflicts with the builting type.

Sign up to request clarification or add additional context in comments.

3 Comments

I edited the original question according to your answer, please have a look. :)
why do you want it in that specific format? As long as you can parse the correct json, why would you be concerned ?
you mean the data structure what I received in js callback? because I don't want to change the code in js callback if the js code is migrated for other background such as ASP.NET MVC, I want to use the data list return from backend with normal model structure. And finally, I changed the return code to return HttpResponse(json.dumps(list(poll_list.values()), cls=DjangoJSONEncoder)) and got desired result.
0
import json

return HttpResponse(json.dumps(Poll.objects.all()), 
                    content_type="application/json")

The above uses json to serializes your queryset. I'm not sure if there are some model fields that could choke when being serialized, so you might want to look at bulit in django serializer


if you have many API endpoints, I would recommend looking at django-rest-framework

2 Comments

Yes, the DateTimeField can't be serialized. I edited the original question, please have a look. By the way, this is only a example project for me to study Django, so I don't want to use another framework such as django-rest-framework. :)
I would say not using django-rest-framework would be a huge mistake. It's tantamount to saying, I want to go fast, but I don't want to use wheels, or wings, or an engine.

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.