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

Los*_*der 4 python django decimal django-models django-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
Run Code Online (Sandbox Code Playgroud)

我需要在视图中获取数据的 json 版本。为此,我正在尝试获取数据的 JSON 转储。使用 json.dumps(resultDict)会引发错误。

从模型尝试不同结果的错误被注释掉以供参考。该dict(zip())选项最接近我想要的结果 resultDict 为我提供了一个我可以使用的 JSON(键、值)配对。但是它给了我一个包含“ DecimalField”的结果数据的错误有没有办法在返回的数据上没有错误的情况下有小数位?看起来这将是 Django 支持的简单事情,所以我不确定我是否遗漏了什么!

https://github.com/pyeve/eve-sqlalchemy/issues/50

另外,我是否可以将 ResultModel 直接处理到视图中的 json 转储中,而不是设置 2 个结果集(具有相同数据,只是格式不同)以从模型发送回视图?

更新:我想通了。由于这是一个存储过程/直接查询,当我们使用时 ORM 映射不起作用 dict(zip(columns, row)),应该使用来自 db 查询的列名。然后,为了让 JSON 做一个json.dumps(myDict)

替代解决方案:在模型中, return [ResultModel(*row) for row in rows]

意见:

results = Get-model
json = serializers.serialize("python", results, fields=('Column1', 'Column2')
Run Code Online (Sandbox Code Playgroud)

但这也给了我模型名称。有没有办法只返回每个列表的 .fields 部分?

[字段:{Column1:“1”,Column2:“2”},模型:“app_name.resultmodel”,pk:“”]

HP *_*una 11

尝试扩展 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)
Run Code Online (Sandbox Code Playgroud)