Skip to content

Instantly share code, notes, and snippets.

@alexpirine
Last active November 12, 2018 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexpirine/968f63cc4069d1ce6e6c to your computer and use it in GitHub Desktop.
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
# 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)
@snekse
Copy link

snekse commented Jun 29, 2018

You posted a public gist w/ a copyright?

@alesanchezr
Copy link

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