Javascript – Passing objects from Django to Javascript DOM

djangodomjavascriptjsonpython

I'm trying to pass a Query Set from Django to a template with javascript.

I've tried different approaches to solve this:

1. Normal Approach – Javascript gets all messed up with trying to parse the object because of the nomenclature [ &gt Object:ID &lt, &gt Object:ID &lt,… ]

Django View

django_list = list(Some_Object.objects.all())

Template HTML + JS

<script type="text/javascript" >
    var js_list = {{django_list}};
</script>

2. JSON Approach – Django fails on converting the object list to a json string
is not JSON serializable

Django View

django_list = list(Some_Object.objects.all())
json_list = simplejson.dumps(django_list)

Template HTML + JS

<script type="text/javascript" >
    var js_list = {{json_list}};
</script>

So, I need some help here 🙂

Any one has any suggestion / solution?

Thanks!

Best Answer

Same Question, "Better"(more recent) answer: Django Queryset to dict for use in json

Answer by vashishtha-jogi:

A better approach is to use DjangoJSONEncoder. It has support for Decimal.

import json
from django.core.serializers.json import DjangoJSONEncoder

prices = Price.objects.filter(product=product).values_list('price','valid_from')

prices_json = json.dumps(list(prices), cls=DjangoJSONEncoder)

Very easy to use. No jumping through hoops for converting individual fields to float.

Update : Changed the answer to use builtin json instead of simplejson.

This is answer came up so often in my google searches and has so many views, that it seems like a good idea to update it and save anyone else from digging through SO. Assumes Django 1.5.