miki725
miki725

Reputation: 27861

Serialize models in django with proper decimal data types into json

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.

Upvotes: 2

Views: 4436

Answers (1)

jathanism
jathanism

Reputation: 33716

If the value actually 50 vs. 50.0? A Decimal object maintains whatever was originally input, e.g. Decimal('50') yields 50.

>>> from decimal import Decimal
>>> d = Decimal('50')
>>> print d
50

Unfortunately the arguments provided to the DecimalField constructor 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:

import decimal
import json
class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return '%.2f' % obj # Display Decimal obj as float
        return json.JSONEncoder.default(self, obj)

But it doesn't end there. As detailed in this blog post, Django is explicitly passing cls=DjangoJSONEncoder to simplejson.dump(...), so we have to circumvent this by also creating a custom serializer object referencing the DecimalEncoder we created:

from django.core.serializers.json import Serializer as JSONSerializer
class DecimalSerializer(JSONSerializer):
    def end_serialization(self):
        self.options.pop('stream', None)
        self.options.pop('fields', None)
        json.dump(self.objects, self.stream, cls=DecimalEncoder, **self.options)

Next, you instantiate DecimalSerializer as your own serializer object, and magic happens:

my_serializer = DecimalSerializer()
print my_serializer.serialize([obj], indent=4)

Which yields:

[
    {
        "pk": 1, 
        "model": "app.foomodel", 
        "fields": {
            "foo": "50.00"
        }
    }
]

This seems like a lot of work. It might just be easier to use Django's model validation to make sure that a FooModel.foo field is always a floating point number, prior to saving. Here is brute force attempt at that:

from django.core.exceptions import ValidationError

class FooModel(models.Model):
    foo = models.DecimalField(max_digits=6, decimal_places=3, null=True)

    def clean(self):
        if '.' not in str(self.foo):
            raise ValidationError('Input must be float!')

    def save(self, *args, **kwargs):
        self.full_clean()
        super(FooModel, self).save(*args, **kwargs)

And then:

>>> f = FooModel(foo='1')
>>> f.save()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/jathan/sandbox/foo/app/models.py", line 15, in save
    self.full_clean()
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 828, in full_clean
    raise ValidationError(errors)
ValidationError: {'__all__': [u'Input must be float!']}

Upvotes: 4

Related Questions