0

I have a django app with rest framework and I noticed that some DecimalField are serialized as string, others as numbers. Why? Here's my model:

class TestModel(models.Model):
   quantity1 = models.DecimalField("quantity1", default=0.0, max_digits=10, decimal_places=3)
   quantity2 = models.DecimalField("quantity2", default=0.0, max_digits=10, decimal_places=3)
   quantity3 = models.DecimalField("quantity3", default=0.0, max_digits=10, decimal_places=3)

   latitude = models.DecimalField(max_digits=9, decimal_places=6)
   longitude = models.DecimalField(max_digits=9, decimal_places=6)

Here's the serialization

"quantity1": "1.000",
"quantity2": "1.000",
"quantity3": "1.000",
"latitude": 45.49907,
"longitude": 9.18749,

Here is the serialize class used:

class TestModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = TestModel
        fields = [
            "id",
            "quantity1",
            "quantity2",
            "quantity3",
            "latitude",
            "longitude"
        ]

I am aware of the problem of serialize floating point and their precision (see here), but why quantities are represented as string while lat/lon are numbers? They are both decimalFields...

  • You are not saying how the values are getting serialized, but probably this helps https://stackoverflow.com/a/49770815/183910 – Bernhard Vallant Jul 05 '22 at 08:28
  • Thanks @BernhardVallant. That's help to represent all the decimal as number (if set to False), but I still doesn't understand why, if set to True, some of them are string, other are number – Alessandro Salvetti Jul 05 '22 at 12:03
  • Maybe show us your serializer class as well? And have a look how [`to_representation`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/fields.py#L1119-L1138) of `DecimalField` works... Probably it gets something else than `decimal.Deciaml`? Like an integer? – Bernhard Vallant Jul 05 '22 at 12:08
  • It's a normal Serializer, btw I added it – Alessandro Salvetti Jul 06 '22 at 14:42

0 Answers0