Login

Integer based MoneyField

Author:
Jay
Posted:
September 24, 2009
Language:
Python
Version:
1.1
Tags:
money db field
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. django-pyodbc MoneyField by Tarken 6 years, 8 months ago
  2. Fixed-point Decimal model field with integer storage by lanzz 1 year, 3 months ago
  3. Widget for Money values on Geraldo Reports by marinho 6 years, 2 months ago
  4. Converts an integer or floating-point number or a string to a string containing the delimiter character (default comma) after every delimeter_count digits (by default 3 digits) by pikhovkin 3 years, 3 months ago
  5. Currency Fields with newforms by sago 8 years, 2 months ago

Comments

Please login first before commenting.