所以如果我知道将模型数据序列化为JSON会有多困难,我就不会使用Django的DecimalField
选项。
长话短说,如何从DecimalField
获得浮动值?
我的模型看起来像这样:
class DailyReport(models.Model):
earnings = models.DecimalField(max_digits=12, decimal_places=4)
def earnings_float(self):
return self.earnings.to_float()
显然没有to_float()
方法可用,所以我该怎么做呢?
以下是后来的补充:
这有效:
class DailyReport(models.Model):
earnings = models.DecimalField(max_digits=12, decimal_places=4)
def earnings_float(self):
return float(self.earnings)
但即使这看起来太复杂了。我正在尝试使用django-rest-framework进行所有序列化,因为我通常在我的应用程序中使用它作为rest-framework的东西。在这种特殊情况下,我只想将我的数据转换并序列化为python列表和字典,然后通过pymongo 3将它们作为文档存储在Mongo DB中。
答案 0 :(得分:4)
将DecimalField转换为float:
function toggleRep() {
$(".acelity-partner").toggle();
if ($(".acelity-partner").is(":visible")) {
// do nothing
} else {
//clear fields of their values
$(".acelity-rep").val("");
}
}
答案 1 :(得分:2)
浮点数和小数不一样。不要将小数转换为浮点数来序列化它;你会失去精确度。
而只是使用DjangoJSONEncoder类,它可以正常工作:
from django.core.serializers import DjangoJSONEncoder
json.dumps(self.earnings, encoder=DjangoJSONEncoder)
答案 2 :(得分:0)
可能只是让序列化程序将其强制转换为浮点型字段。
rest-framework declaring-serializers
from rest_framework import serializers
class DailyReportSerializer(serializers.ModelSerializer):
earnings = serializers.FloatField()
class Meta:
model = DailyReport
fields = ('earnings',)
答案 3 :(得分:0)
3.0提供了将小数序列化为浮点数的选项。
REST_FRAMEWORK = {
'COERCE_DECIMAL_TO_STRING': False
}