Login

Fixed-point Decimal model field with integer storage

Author:
lanzz
Posted:
March 11, 2014
Language:
Python
Version:
1.6
Tags:
money decimal fixed-point
Score:
0 (after 0 ratings)

Fixed-point model field based on IntegerField and DecimalField. Represented as Decimal in Python for accurate calculations, stored as integer in the database. Configurable decimal places, defaults to 2.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import decimal
from django.db import models
from django.core import exceptions
from django.utils.translation import ugettext_lazy as _

class FixedPointField(models.Field):

    empty_strings_allowed = False
    default_error_messages = {
        'invalid': _("'%(value)s' value must be a decimal number."),
    }
    description = _("Fixed-point number")

    __metaclass__ = models.SubfieldBase

    def __init__(self, verbose_name=None, name=None, decimal_places=2, **kwargs):
        self.decimal_places = decimal_places
        super(FixedPointField, self).__init__(self, verbose_name, name, **kwargs)

    def to_python(self, value):
        if value is None or isinstance(value, decimal.Decimal):
            return value
        try:
            if isinstance(value, int):
                return decimal.Decimal(value) / (10 ** self.decimal_places)
            else:
                return decimal.Decimal(value)
        except decimal.InvalidOperation:
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={'value': value},
            )

    def get_prep_value(self, value):
        return int(value * (10 ** self.decimal_places))

More like this

  1. Integer based MoneyField by Jay 5 years, 11 months ago
  2. 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, 5 months ago
  3. Newforms field for decimals with a comma by jonasvp 7 years, 5 months ago
  4. Currency Fields with newforms by sago 8 years, 4 months ago
  5. Integer Currency Input by jgeewax 6 years, 12 months ago

Comments

Please login first before commenting.