Ticket #5079: 5079_4.diff

File 5079_4.diff, 2.3 KB (added by Philippe Raoult, 17 years ago)

better patch

  • django/db/models/fields/__init__.py

     
    686686        if value < 0:
    687687            num_chars += 1
    688688
    689         return u"%.*f" % (self.decimal_places, value)
     689        if isinstance(value, decimal.Decimal):
     690            if not hasattr(self, '_context'):
     691                self._context = decimal.getcontext().copy()
     692                self._context.prec = self.decimal_places
    690693
     694            return value.quantize(decimal.Decimal('.1')**self.decimal_places, context = self._context)
     695        else:
     696            return u"%.*f" % (self.decimal_places, value)
     697
    691698    def get_db_prep_save(self, value):
    692699        if value is not None:
    693700            value = self._format(value)
  • tests/regressiontests/model_fields/tests.py

     
    1 """
     1
     2
     3from django.db import models
     4from decimal import Decimal
     5
     6class DecimalTest(models.Model):
     7    field = models.DecimalField(max_digits=35, decimal_places=30)
     8
     9__test__ = {'API_TESTS': """
    210>>> from django.db.models.fields import *
    311
    412# DecimalField
     
    1523Traceback (most recent call last):
    1624...
    1725ValidationError: [u'This value must be a decimal number.']
    18 """
     26
     27# added after #5079
     28>>> b1 = DecimalTest(field=Decimal(".1"))
     29>>> b1.field
     30Decimal("0.1")
     31>>> b1.save()
     32>>> b1.field
     33Decimal("0.1")
     34
     35>>> b2 = DecimalTest.objects.get(id=1)
     36>>> b2.field.normalize()
     37Decimal("0.1")
     38
     39# this should fit in
     40>>> b1 = DecimalTest(field=Decimal(".100000000000000000000000000005"))
     41>>> b1.field
     42Decimal("0.100000000000000000000000000005")
     43>>> b1.save()
     44>>> b1.field
     45Decimal("0.100000000000000000000000000005")
     46>>> b2 = DecimalTest.objects.get(id=b1.id)
     47>>> b2.field
     48Decimal("0.100000000000000000000000000005")
     49
     50# this shouldn't!
     51>>> b1 = DecimalTest(field=Decimal(".100000000000000000000000000000000000000000000005"))
     52>>> b1.field
     53Decimal("0.100000000000000000000000000000000000000000000005")
     54>>> b1.save()
     55>>> b2 = DecimalTest.objects.get(id=b1.id)
     56>>> b2.field.normalize()
     57Decimal("0.1")
     58
     59"""}
Back to Top