Login

Integer based MoneyField

Author:
Jay
Posted:
September 24, 2009
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

It is supposed the aggregation on integer is fast than numeric type in database duo to how they are stored as numeric is represented as string. As money only have 2 decimal place, it can be converted to an Integer despite of its decimal point.

The python class decimal.Decimal also has a shortcoming that it is not json serializable(neither cjson nor simplejson). This money field appears as a float number to the front end, so it does not meet the headache as DecimalField.

The usage is very simple.

In Model:

class SomeModel(models.Model):
    ...
    income = MoneyField('income')
    ...

Then treat the attribute of the model instance as a normal float type.

Notes

If you try to use aggregation on this field, you have to convert it to float by yourself. Currently I could not find any method to fix this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.db import models

class MoneyField(models.IntegerField):
    __metaclass__ =  models.SubfieldBase
    
    def get_db_prep_value(self, value):
        if value is None:
            return None
        return int(value * 100)

    def to_python(self, value):
        if value is None or isinstance(value, float):
            return value
        try:
            return float(value) / 100
        except (TypeError, ValueError):
            raise exceptions.ValidationError(
                "This value must be an integer or a string represents an integer.")

    def formfield(self, **kwargs):
        from django.forms import FloatField
        defaults = {'form_class': FloatField}
        defaults.update(kwargs)
        return super(MoneyField, self).formfield(**defaults)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.