1

我需要UPDATE sometable SET total_cost=cost*sec/60.0通过 Django ORM 执行查询。查询将产生一些类似于票证中描述的问题的警告。

new_records = Service.objects.filter(upd='U')

print new_records.update(
    total_cost=F('cost')*F('billsec')/Decimal('60.0')
)

cost&&sec字段是 DECIMAL(10,4) 类型)。结果:

Traceback (most recent call last):
File "./test.py", line 15, in <module>
    total_cost=F('cost')*F('billsec')/Decimal('60.0')
File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 533, in update
    rows = query.get_compiler(self.db).execute_sql(None)
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 986, in execute_sql
    cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 818, in execute_sql
    cursor.execute(sql, params)
File "/usr/lib/python2.7/dist-packages/django/db/backends/util.py", line 40, in execute
    return self.cursor.execute(sql, params)
File "/usr/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 114, in execute
    return self.cursor.execute(query, args)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 176, in execute
    if not self._defer_warnings: self._warning_check()
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 92, in _warning_check
    warn(w[-1], self.Warning, 3)
_mysql_exceptions.Warning: Data truncated for column 'total_cost' at row 1

如果我Decimal()从过滤器查询中删除,它将正常工作。

4

1 回答 1

1

请参阅此 Django 票 https://code.djangoproject.com/ticket/13666

据说这是MySQL错误处理十进制字符串的问题。有人说将小数转换为浮点数,即 float(Decimal('60.0')) 应该可以解决问题。

于 2014-02-17T13:04:25.617 回答