首页 > 解决方案 > 如何使用 Django 将存储为 JSON 的十进制数字转换为十进制?

问题描述

我使用 Django 在 JSONField 中存储十进制数字,以便拥有灵活的数字数量,但后来我无法使用它们。这就是我的模型的样子。

from decimal import Decimal
# from django.core.serializers.json import DjangoJSONEncoder
import simplejson

class Order(models.Model):
    account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True)
    size = JSONField(null=True)

按照此答案https://stackoverflow.com/a/3148376/3423825的建议并存储如下值:

import simplejson as json
self.size = json.dumps(Decimal('1'), use_decimal=True)

现在,当我尝试将其转换为十进制时,出现错误。

size = Decimal(self.size)

Object of type 'Decimal' is not JSON serializable

我必须说我有点迷路,因为type(self.size)返回<class string>所以我应该能够将它转换为Decimal,或者我错过了什么?

谢谢

标签: pythondjango

解决方案


推荐阅读