2016-04-19 222 views
1

我的一個模型領域如下:Django「DecimalFields必須定義'decimal_places'屬性。」

aaf_1kg_all = models.DecimalField(blank=True, null=True) 

當我使用我的模型一般,一切都很好。當我在一個ready() hook使用它,但是,我得到這個錯誤:

SystemCheckError: System check identified some issues: 

ERRORS: 
myapp.Model.aaf_1kg_all: (fields.E130) DecimalFields must define a 'decimal_places' attribute. 
myapp.Model.aaf_1kg_all: (fields.E132) DecimalFields must define a 'max_digits' attribute. 

Django文檔說,這兩個屬性是可選的。我看到了this answer,但在數據庫中定義了小數位數和max_digits。

如果我決定要添加這些屬性,即

aaf_1kg_all = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=10) 

的應用程序運行,但在某些時候我得到這個錯誤,而不是:

Traceback (most recent call last): 
[...] 
    variants.extend(list(sub_qs)) # sub_qs is a QuerySet 
File ".../django/db/models/query.py", line 258, in __iter__ 
    self._fetch_all() 
File ".../django/db/models/query.py", line 1074, in _fetch_all 
    self._result_cache = list(self.iterator()) 
File ".../django/db/models/query.py", line 68, in __iter__ 
    for row in compiler.results_iter(results): 
File ".../django/db/models/sql/compiler.py", line 808, in results_iter 
    row = self.apply_converters(row, converters) 
File ".../django/db/models/sql/compiler.py", line 792, in apply_converters 
    value = converter(value, expression, self.connection, self.query.context) 
File ".../django/db/backends/sqlite3/operations.py", line 233, in convert_decimalfield_value 
    value = expression.output_field.format_number(value) 
File ".../django/db/models/fields/__init__.py", line 1608, in format_number 
    return utils.format_number(value, self.max_digits, self.decimal_places) 
File ".../django/db/backends/utils.py", line 200, in format_number 
    value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context) 
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] 

我是不是忘了什麼東西?

+1

的'max_digits'和'decimal_places'參數是可選的爲[表單字段](https://docs.djangoproject.com/en/1.9/ref/forms/fields/#decimalfield )。它們是[模型字段]必需的(https://docs.djangoproject.com/en/1.9/ref/models/fields/#decimalfield)。 – Alasdair

+0

這個鏈接http://stackoverflow.com/questions/33827179/python-decimal-invalidoperation-error將幫助你解決你的錯誤 –

+0

我不明白downvotes,但得到一個答案是重要的。感謝人們。 – JulienD

回答

6

max_digits應該比decimal_places

注意0.1000000000使用10位數字更大,但1.0000000000使用11位。因此,如果您有max_digits=10decimal_places=10,則任何大於或等於1.0的數字都會給出錯誤。

如果您不需要小數位,那麼您可能需要類似max_digits=10decimal_places=3。或者如果你真的需要decimal_places=10,那麼也許你需要類似max_digits=12,這將支持小於1000的值。

Django 1.9已經添加了一個驗證器來試圖防止這樣的錯誤。有關更多詳細信息,請參閱ticket 24636

+0

如果'max_digits'必須大於'decimal_places',那麼這是一個文檔錯誤。根據[文檔](https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.DecimalField.max_digits),'請注意,此數字必須大於或等於以decimal_places.' –

+2

該文件是正確的,他們可以是相同的。但是,如果它們相同,那麼該字段不能處理大於或等於'1.0'的值。 – Alasdair

4

參數max_digits必須大於decimal_places

例如

aaf_1kg_all = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) 
相關問題