Django:为什么这个自定义模型字段的行为不如预期的那样? [英] Django: Why does this custom model field not behave as expected?
问题描述
以下字段意味着将货币格式化为二进制十进制(量化)。您可以看到它返回存储小数的< decimal> .quantize(TWOPLACES)
版本。然而,当我在Django管理员中查看这个时,它不会这样做。如果我将 50
放在使用 CurrencyField()
的字段中,并在管理员中查看, code> 50 vs 50.00
。为什么是这样?
The following field is meant to format money as a two places decimal (quantized). You can see that it returns a <decimal>.quantize(TWOPLACES)
version of the stored decimal. When I view this in the Django admin however, it doesn't do that. If I put in 50
to a field that is using CurrencyField()
and view it in the admin, I get 50
vs 50.00
. Why is that?
from django.db import models
from decimal import Decimal
class CurrencyField(models.DecimalField):
"""
Only changes output into a quantized format. Everything else is the same.
"""
def __init__(self, *args, **kwargs):
kwargs['max_digits'] = 8
kwargs['decimal_places'] = 2
super(CurrencyField, self).__init__(*args, **kwargs)
def to_python(self, value):
try:
return super(CurrencyField, self).to_python(value).quantize(Decimal('0.01'))
except AttributeError:
return None
更新:我试着把 return'Hello World'
代替 return super(CurrencyField,self).to_python(value).quantize(Decimal ('0.01'))
,甚至没有在shell中显示Hello World。它再次出现 50
。这是否意味着当我访问一个模型的属性是一个 CurrencyField()
时,它不会调用 to_python()
?
Update: I tried putting return 'Hello World'
in place of return super(CurrencyField, self).to_python(value).quantize(Decimal('0.01'))
and it didn't even show 'Hello World' in the shell. It put out 50
again. Does this mean that when I access an attribute of a model that is a CurrencyField()
it doesn't call to_python()
?
推荐答案
也许您可以尝试将其添加到您的字段中:
Maybe you could try adding this to your field:
__metaclass__ = models.SubfieldBase
另见 here 。
这篇关于Django:为什么这个自定义模型字段的行为不如预期的那样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!