Reputation: 161
I'm trailing to get rid of the unwanted trailing zeros for my Django model field:
class mycls(BaseModel):
price = models.DecimalField()
I've even tried to creat a new field. Here is the Django field I created:
class CurrencyField(models.DecimalField):
INTEGER_PLACES = 15
DECIMAL_PLACES = 18
DECIMAL_PLACES_FOR_USER = 6
MAX_DIGITS = INTEGER_PLACES + DECIMAL_PLACES
MAX_VALUE = Decimal('999999999999999.999999999999999999')
MIN_VALUE = Decimal('-999999999999999.999999999999999999')
def __init__(self, verbose_name=None, name=None, max_digits=MAX_DIGITS,
decimal_places=DECIMAL_PLACES, **kwargs):
super().__init__(verbose_name=verbose_name, name=name, max_digits=max_digits,
decimal_places=decimal_places, **kwargs)
By using this function I want to remove the trailing from this field
def normalize_fraction(d):
normalized = d.normalize()
sign, digit, exponent = normalized.as_tuple()
return normalized if exponent <= 0 else normalized.quantize(1)
How can I use this function inside that field class to remove the trailing zeros?
Upvotes: 0
Views: 283
Reputation: 337
You should override from_db_value, try something like this:
class CurrencyField(models.DecimalField):
...
...
...
def from_db_value(self, value, expression, connection):
if value is None:
return value
return normalize_fraction(value)
Upvotes: 1