16

I have the following queryset:

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

How can i get the prices as "json"

{"aaData": [
    ["70.1700", "2007-01-01"], # price, valid_form
    ["72.6500", "2008-01-01"], # price, valid_form
    ["74.5500", "2009-01-01"], # price, valid_form
    ["76.6500", "2010-01-01"]
]}
nelsonvarela
  • 2,310
  • 7
  • 27
  • 43

2 Answers2

43

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.

Vashishtha Jogi
  • 12,120
  • 2
  • 19
  • 20
  • 6
    Just a note... the use of `django.utils.simplejson` has been depricated as of Django 1.5. See the [release notes](https://docs.djangoproject.com/en/dev/releases/1.5/#system-version-of-simplejson-no-longer-used) for more info. – Ngenator Jun 21 '13 at 14:56
  • 4
    following the example shown: once I have `prices_json` how do I pass it over to the template/js? and how do I access it from there? – Maor Apr 26 '15 at 20:04
0
from django.utils import simplejson

prices = Price.objects.filter(product=product).values_list('price', 'valid_from')
simplejson.dumps({'aaData': prices})

Edit

It wasn't clear from your question that price is a DecimalField. It looks like you'd need to convert from Decimal to float:

simplejson.dumps({'aaData': (float(price), valid_from) for price, valid_from in prices})

Alternatively, if you want the price to be a string:

simplejson.dumps({'aaData': (str(price), valid_from) for price, valid_from in prices})
dgel
  • 16,352
  • 8
  • 58
  • 75