ignacio.munizaga
ignacio.munizaga

Reputation: 1603

Django tastypie serializes DecimalField as json strings instead of numbers

I have a django application with tastypie. One of the models in my app has a DecimalField. When I get a response from the API in JSON format, all the decimal fields appear as strings instead of numbers:

For example I get:

objects: [
    {
        id: "1",
        my_decimal_field: "84.54"
    }

instead of

objects: [
    {
        id: "1"
        my_decimal_field: 84.54
    }

This also happens with the id field.

¿Any thoughts?

Upvotes: 3

Views: 699

Answers (1)

Druska
Druska

Reputation: 4941

In JavaScript, JSON decodes to double-precision floating point format, which causes a loss of precision. Decimal objects are encoded to string to maintain precision.

If you want to encode to JSON number format, you can use a FloatField.

Upvotes: 4

Related Questions