Reputation: 768
I'm trying to add two values (one from a method and one from a field) in my Django models.py.
class Object(models.Model):
value = models.DecimalField()
def scaled_value(self):
scaled_val = float(self.value) * 3
return scaled_val
def add_val_and_scaled_val(self):
sum = self.scaled_value + self.value
return sum
When I try to get the value of the sum from the 'add_val_and_scaled_val
' method in my template like this {% Object.add_val_and_scaled_val %}
then I get the TypeError...
TypeError at /objects/detail/object-12345678/
unsupported operand type(s) for +: 'instancemethod' and 'Decimal'
The instancemethod which the error refers to (self.scaled_value
) should return a decimal value should it not? What am I doing wrong? Thanks.
Upvotes: 0
Views: 963
Reputation: 599490
scaled_value
is a method, you need to call it in your calculation not just refer to it.
sum = self.scaled_value() + self.value
(Although I'm not sure of the point of any of this code. x*3 + x just equals x*4, no?)
Upvotes: 1
Reputation: 133514
The instancemethod which the error refers to (self.scaled_value) should return a decimal value should it not
def scaled_value(self):
scaled_val = float(self.value) * 3
return scaled_val
No it shouldn't because in scaled_value
you explicity convert to a float
Also you need to change this code
def add_val_and_scaled_val(self):
sum = self.scaled_value() + self.value # you had self.scaled_value
return sum
You should reconsider adding float
and Decimal
however
Lastly, would recommend against shadowing the builtin sum
function with sum = ...
Upvotes: 0