Last active
November 12, 2018 19:59
-
-
Save alexpirine/968f63cc4069d1ce6e6c to your computer and use it in GitHub Desktop.
Automatically round Django's DecimalField according to the max_digits and decimal_places attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
You posted a public gist w/ a copyright?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You posted a public gist w/ a copyright?