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
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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.