Django - Decimal类型的对象不是JSON可序列化的,并且在视图中转换为模型数据

问题描述 投票:1回答:1
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 / direct查询,当我们使用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部分?

[fields:{Column1:“1”,Column2:“2”},型号:“app_name.resultmodel”,pk:“”]

python django django-models django-views decimal
1个回答
1
投票

尝试扩展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)
© www.soinside.com 2019 - 2024. All rights reserved.