0

我正在使用django-composite-field创建一个货币字段,其中包含一个 Dollar_value 和一个 Dollar_year(即“2008 年的 200 美元”)。

我在 Django 应用程序中有以下模型:

#models.py
from composite_field import CompositeField

class DollarField(CompositeField):
    """ Composite field to associate dollar values with dollar-years."""
    dollar_value = models.DecimalField(max_digits=8, decimal_places=2)
    dollar_year = models.PositiveSmallIntegerField(
        blank=False,
        null=False, 
        validators=[
            MinValueValidator(1980),
            MaxValueValidator(2020)])

    def __unicode__(self):
        return self.dollar_year+"$: $"+self.dollar_value # "2012$: $149.95"

class ProductStandard(models.Model):
    product = models.ForeignKey(Product)
    standard_level = models.ForeignKey(StandardLevel)
    price = DollarField()

当我访问实例的price属性时ProductStandard,我希望看到这样的格式化字符串:2012$: $199.99. 相反,我看到了 CompositeField方法DollarField(dollar_value=Decimal('199.99'), dollar_year=2012)的返回值。但是既然我已经继承了 CompositeField 并添加了我自己的方法,Django 不应该覆盖吗?还是我误解了什么?__repr____unicode__

我将 Django 1.5.4 与 Python 2.7.3 和 django-composite-field 0.1 一起使用。

4

1 回答 1

0

The __repr__ you are seeing is actually not a __repr__ of a CompositeField, but of it's Proxy (refer to composite_field/base.py, line 104). So you would have to provide your own proxy, and override the __repr__ method there, like so:

class DollarField(CompositeField):
    """ Composite field to associate dollar values with dollar-years."""
    dollar_value = models.DecimalField(max_digits=8, decimal_places=2)
    dollar_year = models.PositiveSmallIntegerField(
        blank=False,
        null=False, 
        validators=[
            MinValueValidator(1980),
            MaxValueValidator(2020)])

    def get_proxy(self, model):
        return DollarField.Proxy(self, model)

    class Proxy(CompositeField.Proxy):
        def __repr__(self):
            return "%s$: $%s" % (self.dollar_year, self.dollar_value) # "2012$: $149.95"

of course, if you would like to leave __repr__ as it is, you can override __unicode__ instead of __repr__, like you did. The difference is that:

print(mymodel.price)

would call the __repr__, while

print(unicode(mymodel.price))

would call the __unicode__ method.

于 2013-12-30T18:16:10.497 回答