如果我填充十进制字段,则无法保存模型实例

时间:2013-04-17 19:26:50

标签: python django python-2.7 model decimal

所以这件事发生在我身上:

thing = ModelClass()
thing.foo = bar()
thing.do_Stuff()
thing.save()  #works fine
thing.decimal_field = decimal_value
thing.save()  #error here

跟踪跟踪:

TypeError at /journey/collaborators/2/

unsupported operand type(s) for ** or pow(): 'Decimal' and 'str'

274.             oH.save()
File "/usr/lib/python2.7/dist-packages/django/db/models/base.py" in save
  460.         self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
  543.                         for f in meta.local_fields if not isinstance(f, AutoField)]
File "/usr/lib/python2.7/dist-packages/django/db/models/fields/subclassing.py" in inner
  28.             return func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/db/models/fields/__init__.py" in get_db_prep_save
  787.                 self.max_digits, self.decimal_places)
File "/usr/lib/python2.7/dist-packages/django/db/backends/__init__.py" in value_to_db_decimal
  705.         return util.format_number(value, max_digits, decimal_places)
File "/usr/lib/python2.7/dist-packages/django/db/backends/util.py" in format_number
  145.         return u'%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))

我尝试将decimal_value设置为decimal.Decimal实例,浮点数,int和字符串。我似乎无法保存我的模型实例,除非我将该字段留空。

任何想法如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

在堆栈跟踪中,它看起来像decimal_places

return u'%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))

str并且您正在尝试执行不允许powDecimal类型的操作(str

因此,您可以尝试将decimal_places更改为int(decimal_places),或找出原因为str而不是int

答案 1 :(得分:0)

修正了它。我改变了:

 decimal_field = models.DecimalField(decimal_places='2',max_digits='6',null=True)

 decimal_field = models.DecimalField(decimal_places=2,max_digits=6,null=True)