【问题标题】:Django: Why does this custom model field not behave as expected?Django:为什么这个自定义模型字段的行为不符合预期?
【发布时间】:2010-01-18 02:36:52
【问题描述】:

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

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    也许您可以尝试将其添加到您的字段中:

    __metaclass__ = models.SubfieldBase
    

    另见here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      相关资源
      最近更新 更多