Login

Automatically round Django's DecimalField according to the max_digits and decimal_places attributes

Author:
alexpirine
Posted:
February 8, 2016
Language:
Python
Version:
Not specified
Tags:
field decimal
Score:
1 (after 1 ratings)

This snippet allows you to use a new field type, RoundedDecimalField, that will automatically round any value affected to it according to the max_digits and decimal_places attributes. You will no longer receive validation errors if you use a float or a decimal with too many decimal digits.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# coding: utf-8
# Copyright (c) Alexandre Syenchuk (alexpirine), 2016

import decimal

from django.db import models

class RoundedDecimalField(models.DecimalField):
    """
    Usage: my_field = RoundedDecimalField("my field", max_digits = 6, decimal_places = 2)
    """
    def __init__(self, *args, **kwargs):
        super(RoundedDecimalField, self).__init__(*args, **kwargs)
        self.decimal_ctx = decimal.Context(prec = self.max_digits, rounding = decimal.ROUND_HALF_UP)
    
    def to_python(self, value):
        res = super(RoundedDecimalField, self).to_python(value)
        
        if res is None:
            return res
        
        return self.decimal_ctx.create_decimal(res).quantize(decimal.Decimal(10) ** - self.decimal_places)  

More like this

Comments

Please login first before commenting.