Django:DecimalField接受浮点数,但这应该抛出一个错误

时间:2012-09-26 07:40:08

标签: django decimal

我有一个带小数字段的Django模型:

class User(models.Model):
    ...
    balance = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    ...

我的应用程序在我的开发机器上运行(Python 2.7.1,Mac OSX,Django 1.4,MySQL InnoDB),以及生产服务器(Python 2.6.5,Ubuntu,Django 1.4,MySQL ISAM)

问题出在我的开发机器上。此代码无需抛出错误即可运行:

>>> u = User.objects.get(pk=1)
>>> u.balance
Decimal('9.00')
>>> u.balance=1.44
>>> u.save()
>>> u.balance
1.44

据我了解,u.save()应该通过以下错误,它在我的生产实例上执行:

>>> u.save()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 463, in save
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 529, in save_base
    rows = manager.using(using).filter(pk=pk_val)._update(values)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 557, in _update
    return query.get_compiler(self.db).execute_sql(None)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 986, in execute_sql
    cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 808, in execute_sql
    sql, params = self.as_sql()
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 951, in as_sql
    val = field.get_db_prep_save(val, connection=self.connection)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.py", line 873, in get_db_prep_save
    return connection.ops.value_to_db_decimal(self.to_python(value),
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.py", line 847, in to_python
    return decimal.Decimal(value)
  File "/usr/lib/python2.6/decimal.py", line 649, in __new__
    "First convert the float to a string")
TypeError: Cannot convert float to Decimal.  First convert the float to a string

那么为什么我的开发实例不会抛出此错误?问题出现了,因为我检查了一些通过我的单元测试的错误代码。应该抛出此错误。我提出了我的环境细节,因为它必须归因于其中一个差异。我怀疑MySQL ISAM与InnoDB相比,但完全不确定。

谢谢!

1 个答案:

答案 0 :(得分:4)

运行Python 2.7的开发环境不应该抛出该错误,但运行Python 2.6的生产环境应该。

来自Decimal objects上的Python文档:

  

在版本2.7中更改:现在允许构造函数的参数为​​float实例。