[Answered ]-Override + operator for django field

1👍

First, create another class which inherits from int:

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

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

And then return an instance of this class in the to_python method of the field:

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)
👤DhhJmm

1👍

When you do myobj.myfield, you’re accessing an object of the type returned by the field’s to_python method, not the field itself. This is due to some of Django’s metaclass magic.


You probably want to override these methods on the type returned by this method.

Leave a comment