Class 'DecimalField' does not define '__sub__', so the '-' operator cannot be used on its instances

Viewed 419

I am programming a property in Django which is supposed to gather its value from subtracting two models.DecimalField. Yet Pycharm is telling me that (see title).

How could it be that two decimals cannot be operated?

Example code

_profit = models.DecimalField(max_digits=10, decimal_places=2)

amount_in_crypto = models.DecimalField(_('amount in Crypto'), max_digits=10, decimal_places=7)
crypto_market_price = models.DecimalField(_('Crypto market price'), max_digits=10, decimal_places=2)
crypto_sell_price = models.DecimalField(_('Crypto sell price'), max_digits=10, decimal_places=2)

@property
def profit(self):
    return (self.crypto_sell_price - self.crypto_market_price) * self.amount_in_crypto
profit.fget.short_description = _('profit')

Warning: enter image description here

I have inspected Django DecimalField's code and indeed it does not define __sub__ and it inherits from field (which wouldn't make any sense to implement that method), so warning seems correct but question is: Why doesn't Django implement mathematical operations in DecimalField? Is there a reason? Am I missing sth?

1 Answers

I am programming a property in Django which is supposed to gather its value from subtracting two models.DecimalField.

No, you want to subtract two Decimal objects, not the fields that contain these.

While pylint is an effective tool, it can sometimes not understand the meta-logic, and especially not the one that Django has implemented. Pylint thus thinks that self.crypto_sell_price will be a DecimalField, but in reality it is a Decimal object.

You can work with pylint-django [PyPi] instead, which can understand more of the logic that Django has implemented, although that tool can still fail to understand certain logic.

Related