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

橙三吉。 提交于 2019-12-21 18:29:25

问题


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

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()?


回答1:


Maybe you could try adding this to your field:

__metaclass__ = models.SubfieldBase

Also see here.



来源:https://stackoverflow.com/questions/2083591/django-why-does-this-custom-model-field-not-behave-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!