[Fixed]-Django Queryset to dict for use in json

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.

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

Leave a comment