Login

Fixed-point Decimal model field with integer storage

Author:
lanzz
Posted:
March 11, 2014
Language:
Python
Version:
1.6
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. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.