[Fixed]-The DECIMAL type field fetch data become string

43👍

The default decimal representation in Django REST framework is string. To disable this behavior, add following to your settings.py file:

REST_FRAMEWORK = {
    'COERCE_DECIMAL_TO_STRING': False,
    # Your other settings
    ...
}

See details in the documentation.

6👍

The default behaviour of the Decimal field is string in REST_FRAMEWORK to override for the whole app we can use

REST_FRAMEWORK = {
    'COERCE_DECIMAL_TO_STRING': False,
    # Your other settings
    ...
}

but if You want to override it for one field You can do as following

field = serializers.DecimalField(coerce_to_string=False)

by default coerce_to_string is True.
checkout this out

5👍

It is a string because otherwise you’ll get rounding errors. This can be easily seen using a Python shell:

>>> import decimal
>>> from decimal import Decimal
>>> Decimal(0.3)
Decimal('0.299999999999999988897769753748434595763683319091796875')
>>> Decimal('0.3')
Decimal('0.3')
>>> 

Also note that JSON doesn’t have decimal. Only integers and floats.

Leave a comment