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
- Apache strips down "Authorization" header
- How to specify long url patterns using Regex so that they follow PEP8 guidelines
- How to create a 8 digit Unique ID in Python?
- Django – Change a ForeignKey relation to OneToOne
Source:stackexchange.com