I have the following queryset:
我有以下queryset:
prices = Price.objects.filter(product=product).values_list('price', 'valid_from')
How can i get the prices as "json"
我如何得到“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"]
]}
2 个解决方案
#1
38
A better approach is to use DjangoJSONEncoder. It has support for Decimal
.
更好的方法是使用DjangoJSONEncoder。它支持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.
更新:更改了使用内置json而不是simplejson的答案。
#2
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
:
从您的问题中不清楚价格是否为DecimalField。看起来你需要从Decimal转换为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})
#1
38
A better approach is to use DjangoJSONEncoder. It has support for Decimal
.
更好的方法是使用DjangoJSONEncoder。它支持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.
更新:更改了使用内置json而不是simplejson的答案。
#2
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
:
从您的问题中不清楚价格是否为DecimalField。看起来你需要从Decimal转换为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})