[英]Object of type decimal is not JSON serializable error in Django
[英]Django - Object of type Decimal is not JSON serializable and convert to model data in views
rows = fetchall()
resultList = []
resultModel = []
resultDict = []
for row in rows:
resultModel.append(ResultModel(*row)) # Object of type ResultModel is not JSON serializable
resultList.append(list(row)) # Rows returned by pyodbc are not JSON serializable
resultDict.append(dict(zip(columns, row))) # Object of type Decimal is not JSON serializable
我需要在视图中获取数据的json版本。 为此,我正在尝试获取数据的JSON转储。 使用json.dumps(resultDict)
会引发错误。
尝试从模型获得不同结果的错误已注释掉以供参考。 dict(zip())
选项与我想要的结果最接近。resultDict为我提供了可以使用的JSON(键,值)配对。 但这给我一个包含' DecimalField
'的结果数据的错误,有没有办法让小数位数在返回的数据上没有错误? 看来这将是Django支持的简单操作,所以我不确定是否丢失了某些内容!
https://github.com/pyeve/eve-sqlalchemy/issues/50
另外,我是否可以将ResultModel直接处理到视图的json转储中,而不是设置2个结果集(具有相同的数据,只是格式不同)以从模型发送回视图?
更新 :我想通了。 由于这是一个存储的proc /直接查询,因此当我们使用dict(zip(columns, row))
时,ORM映射不起作用,应使用db查询中的列名。 然后,为了获取JSON,请执行json.dumps(myDict)
替代解决方案:在模型中, return [ResultModel(*row) for row in rows]
浏览次数:
results = Get-model
json = serializers.serialize("python", results, fields=('Column1', 'Column2')
但这也给了我型号名称。 有没有办法只返回每个列表的.fields部分?
[栏位:{Column1:“ 1”,Column2:“ 2”},模型:“ app_name.resultmodel”,pk:“”]
尝试扩展JSONEncoder
import json
from decimal import Decimal
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
# Usage:
d = Decimal("42.5")
json.dumps(d, cls=DecimalEncoder)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.