以下字段用于将货币格式化为两位小数(量化)。您可以看到它返回存储的十进制的<decimal>.quantize(TWOPLACES)
版本。但是,当我在Django管理员中查看它时,它不会这样做。如果我将50
放入使用CurrencyField()
的字段并在管理员中查看,我会获得50
vs 50.00
。那是为什么?
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()
?