2

I have problem statement where I need that my field should store the value as decimal, but while calling it the field should return a rounded Integer value

Example

mymodel.myfield = 12.61

mymodel.save()

Input

mymodel.myfield

Output

13

and if it is possible

mymodel.myfield.get_raw

Output

12.61

Can I use django custom model field?

class MyField(models.DecimalField):

    def __init__(self, verbose_name=None, name=None, max_digits=None,
                 decimal_places=None, **kwargs):
        super(MyField, self).__init__(*args, **kwargs)

    def get_raw(self, value):
        return value

    def to_python(self, value):
        if value is None:
            return value
        try:
            return decimal.Decimal(value)
        except decimal.InvalidOperation:
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={'value': value},
            )
abhyuday
  • 126
  • 1
  • 9
  • wouldn't it be easier to store as DecimalField like you did and just call int(my_float) whenever you need it rounded?! – devdob Mar 09 '19 at 11:04
  • @devdob yeah it would be easier, but I have to remember that the value returned is decimal and not int, use this casting every time I use the function – abhyuday Mar 09 '19 at 11:18

0 Answers0