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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.