0

I want to return rate, but got this error in admin unsupported operand type(s) for +: 'NoneType' and 'NoneType'

class SomeModel(models.Model): 
      code_style_rate = models.DecimalField(max_digits=4, decimal_places=2)
      decision_rate = models.DecimalField(max_digits=4, decimal_places=2)
      severity_rate = models.DecimalField(max_digits=4, decimal_places=2)

      @property
      def rate(self):
         return (self.code_style_rate + self.decision_rate + self.severity_rate) / 3


      def __str__(self):
         return self.rate
Alexx
  • 39
  • 3

2 Answers2

1

First you can check if the object is None or not and then perform the calculation.

@property
def rate(self):
   if self.code_style_rate is not None and self.decision_rate is not None and self.severity_rate is not None:
       return (self.code_style_rate + self.decision_rate + self.severity_rate) / 3
arjun
  • 7,230
  • 4
  • 12
  • 29
  • It's recommended to use `if val is not None` instead of `if val`. Please check this thread https://stackoverflow.com/a/7816373/1331040 For example, if `code_style_rate` is `0` this condition becomes falsy. – Harun Yilmaz Sep 23 '20 at 14:56
  • @HarunYilmaz Thanks for the suggestion. – arjun Sep 23 '20 at 14:58
1

I assume, this would be more pythonic,

class SomeModel(models.Model):
    # other fields and methods
    @property
    def rate(self):
        total = (self.code_style_rate or 0) + (self.decision_rate or 0) + (self.severity_rate or 0)
        return total / 3
JPG
  • 82,442
  • 19
  • 127
  • 206