簡體   English   中英

Django-Decimal類型的對象不可JSON序列化,並在視圖中轉換為模型數據

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM