I want to put a Django model in de response for my Ajax request. Currently I have this in my views.py:
def get_account(request, account_id):
try:
account = Account.objects.get(pk=account_id)
success = True
error_message = None
except Account.DoesNotExist:
success = False
error_message = 'This account does not exist'
results = {
'success': success,
'error_message': error_message,
}
return HttpResponse(
json.dumps(results),
mimetype='application/json')
I would like to add the account model to the results dict. account.__dict__ won’t do because it will have references to other objects in it.
I found de django serialize function, which serializes it exactly how I want it, only it makes a Json string directly, so I’ll end up with a Json string inside a Json object (bad for bandwith if you have large models, because the Json string get’s escaped all over). So then I would need to json_decode it another time in Javascript.
Also, the django serialize function only accepts lists of objects, so I would have to make a list with only one object, and when I unserialize it take the first value of the list (which isn’t a super big problem, but it adds up to the pile).
It would be great if you could serialize a model to just a python dict. Then you can do anything with it as you like.
Anyone ever got the same problem? How did you solve it?
With the help of Daniel’s answer I was able to do it:
Because I’m sending it over Ajax, I needed everything to be a string. If you serialize using the ‘python’ method, some things like a datetime field will have a function in it (like
datetime.date(2012, 12, 23)). This function makes a dict with only string values.