Here is a sample model:
class FooModel(models.Model):
foo = models.DecimalField(max_digits=6, decimal_places=3, null=True)
Serialize:
from django.core import serializers
obj = get_object_or_404(FooModel, pk=1)
data = serializers.serialize("json", [obj])
That will return something like:
[
{
"pk": 1,
"model": "app.foomodel",
"fields": {
"foo": "50"
}
}
]
Question
How can I make foo field to serialize as float, and not as string. I don’t want to use float model type since float sometimes does not store decimals correctly.
Thank you in advance.
If the value actually
50vs.50.0? ADecimalobject maintains whatever was originally input, e.g.Decimal('50')yields50.Unfortunately the arguments provided to the
DecimalFieldconstructor are only for restrictions on storing the values and not displaying them.Now, because Django is just using the standard json/simplejson lib, you can specify a custom encoder when serializing, such as suggested in this question:
But it doesn’t end there. As detailed in this blog post, Django is explicitly passing
cls=DjangoJSONEncodertosimplejson.dump(...), so we have to circumvent this by also creating a custom serializer object referencing theDecimalEncoderwe created:Next, you instantiate
DecimalSerializeras your own serializer object, and magic happens:Which yields:
This seems like a lot of work. It might just be easier to use Django’s model validation to make sure that a
FooModel.foofield is always a floating point number, prior to saving. Here is brute force attempt at that:And then: