DECIMAL 类型字段取数据变成字符串

244*_*boy 0 python django django-rest-framework

在我的表中:

我的折扣类型是 DECIMAL:

enter image description here

我在表中的数据:

enter image description here

但是为什么当我在 API 中获取数据时,会得到字符串?

enter image description here

我使用 Django/Django-Rest-Framework 作为后端。


编辑

belong_product:"?????"
ctime:"2018-04-11T15:41:15.744959+08:00"
desc: ""
discount:"0.005"
id : 1
is_enable :false
max_count:5
min_count:0
name:"???????"
uptime:"2018-04-11T15:41:15.745226+08:00"
Run Code Online (Sandbox Code Playgroud)

我的 ListAPI 视图:

class DiscountItemByUserOwnCountListAPIView(ListAPIView):
    serializer_class = DiscountItemByUserOwnCountSerializer
    permission_classes = [IsSuperAdmin]
    pagination_class = CommonPagination   
    def get_queryset(self):   
        return DiscountItemByUserOwnCount.objects.all()
Run Code Online (Sandbox Code Playgroud)

我的型号:

class DiscountItemByUserOwnCount(models.Model):
    name = models.CharField(max_length=16, help_text="??")
    desc = models.CharField(max_length=512, null=True, blank=True, help_text="??")
    min_count = models.IntegerField(help_text="???????")
    max_count = models.IntegerField(help_text="???????")  # ??~?? ????
    discount = models.DecimalField(max_digits=4, decimal_places=3, default=0.000, unique=True,
                                   help_text="??")  # ??: 0.001
    belong_product = models.CharField(max_length=16, help_text="?????DISCOUNT_PRODUCT_TYPE?????")

    is_enable = models.BooleanField(default=False, help_text="????")

    ctime = models.DateTimeField(auto_now_add=True)
    uptime = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ['min_count', '-id']
Run Code Online (Sandbox Code Playgroud)

nev*_*ner 11

DRF 中的默认十进制表示是字符串,要禁用此行为,请在 settings.py 中添加以下内容:

REST_FRAMEWORK = {
    'COERCE_DECIMAL_TO_STRING': False,
    # Your other settings  
    ... 
}
Run Code Online (Sandbox Code Playgroud)

请参阅文档中的详细信息。


fir*_*sne 8

Decimal 字段的默认行为是 REST_FRAMEWORK 中的字符串,以覆盖我们可以使用的整个应用程序

REST_FRAMEWORK = {
    'COERCE_DECIMAL_TO_STRING': False,
    # Your other settings
    ...
}
Run Code Online (Sandbox Code Playgroud)

但如果您想覆盖一个字段,您可以执行以下操作

field = serializers.DecimalField(coerce_to_string=False)
Run Code Online (Sandbox Code Playgroud)

默认情况下coerce_to_stringTrue. 结帐这个


Lin*_*via 5

它是一个字符串,否则你会得到舍入错误。使用 Python shell 可以很容易地看到这一点:

>>> import decimal
>>> from decimal import Decimal
>>> Decimal(0.3)
Decimal('0.299999999999999988897769753748434595763683319091796875')
>>> Decimal('0.3')
Decimal('0.3')
>>> 
Run Code Online (Sandbox Code Playgroud)

另请注意,JSON 没有小数。仅整数和浮点数。

  • COERCE_DECIMAL_TO_STRING 默认为 True。如果将其设置为 False,您将得到浮点数而不是字符串,并且会丢失小数精度,请注意这一点。 (2认同)