Django Queryset字典用于json [英] Django Queryset to dict for use in json
本文介绍了Django Queryset字典用于json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下查询集:
prices = Price.objects.filter(product=product).values_list('price', 'valid_from')
我如何获取价格为 json
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"]
]}
推荐答案
一种更好的方法是使用 DjangoJSONEncoder 。它支持十进制
。
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)
非常易于使用。将各个字段转换为 float
的过程无所不包。
Very easy to use. No jumping through hoops for converting individual fields to float
.
更新:更改了使用内置json而不是simplejson的答案。
Update : Changed the answer to use builtin json instead of simplejson.
这篇关于Django Queryset字典用于json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文