nelsonvarela
nelsonvarela

Reputation: 2370

Django Queryset to dict for use in json

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"]
]}

Upvotes: 16

Views: 30243

Answers (2)

Vashishtha Jogi
Vashishtha Jogi

Reputation: 12210

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.

Upvotes: 43

dgel
dgel

Reputation: 16806

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})

Upvotes: 0

Related Questions