1

我想覆盖 Django 字段的 +- 运算符:

x+y --> x | y    (bitwise or)
x-y --> x & (~y) (almost the inverse of above)

在哪里放置覆盖定义?下面是错误的:

class BitCounter(models.BigIntegerField):
    description = "A counter used for statistical calculations"
    __metaclass__ = models.SubfieldBase    

    def __radd__(self, other):
       return self | other

   def __sub__(self, other):
      return self & (^other)
4

2 回答 2

1

当您这样做时myobj.myfield,您访问的是由字段to_python方法返回的类型的对象,而不是字段本身。这是由于 Django 的一些元类魔法。


您可能希望在此方法返回的类型上覆盖这些方法。

于 2013-02-22T22:02:12.000 回答
1

首先,创建另一个继承自 int 的类:

class BitCounter(int):
    def __add__(self, other):
        return self | other

    def __sub__(self, other):
        return self & (~other)

然后在字段的 to_python 方法中返回这个类的一个实例:

class BitCounterField(models.BigIntegerField):
    description = "A counter used for statistical calculations"
    __metaclass__ = models.SubfieldBase    

    def to_python(self, value):
        val = models.BigIntegerField.to_python(self, value)
        if val is None:
            return val
        return BitCounter(val)
于 2013-02-22T22:15:01.690 回答