Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6871875
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T03:51:27+00:00 2026-05-27T03:51:27+00:00

Here is a sample model: class FooModel(models.Model): foo = models.DecimalField(max_digits=6, decimal_places=3, null=True) Serialize: from

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T03:51:28+00:00Added an answer on May 27, 2026 at 3:51 am

    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!']}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For the following models: class Price: cad = models.DecimalField(max_digits=8, decimal_places=2) usd = models.DecimalField(max_digits=8, decimal_places=2)
I have this sample model working with the admin class Author(models.Model): name = models.CharField(_('Text
Here is my model_users class (the model it extends from doesn't have anything yet
I have two models like so: class Visit(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=65535,
I have a model with a custom method. Here's the example: class MyModel(models) id
Here is my sample code: from xml.dom.minidom import * def make_xml(): doc = Document()
Here is a sample from Kernighan & Ritchie's The C Programming Language: int getline(char
Here is a sample code to retrieve data from a database using the yield
Here is a sample code: public class TestIO{ public static void main(String[] str){ TestIO
Here's simple view model that I use: public class ViewModel { public Order Order

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.