开发者

Django: Why does this custom model field not behave as expected?

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 m开发者_开发百科odels
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

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

Also see here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜