1

i want to calculate multiplication of amount and percent field:

class Info_data(models.Model):
    name = models.CharField(blank=True, max_length=100)
    amount = models.DecimalField(max_digits=5, decimal_places=0)
    percent = models.ForeignKey(Owner, related_name="percentage")

then write this property:

def _get_total(self):
    return self.percent * self.amount
total = property(_get_total)

and use in template:

{% for list_calculated in list_calculateds %}
<ul>
    <li>{{list_calculated.name}}</li>
    <li>{{list_calculated.total}}</li>
</ul>
{% endfor %}

but return blank. how to use property in template?

Ehsan
  • 604
  • 7
  • 21
  • You can't multiply a Decimal object (your amount field) with an Owner object (your percent field) - there's an error there but the template language is hiding it. Fix the logic and it will work. – Ben Mar 12 '17 at 10:05
  • oww. yes, tanks – Ehsan Mar 12 '17 at 10:12

3 Answers3

1

my problem solved by some property edit:

def _get_total(self):
        # return float(self.percent.percent) * float(self.amount)
        return float(self.percent.percent) * float(self.amount)
    total = property(_get_total)
Ehsan
  • 604
  • 7
  • 21
1

Your initial attempt isn't working because you are ignoring the signature of the property-function.

And then your solution could be improved with the help of the property-decorator:

@property
def total(self):
    return self.percent.percent * self.amount
Community
  • 1
  • 1
arie
  • 18,737
  • 5
  • 70
  • 76
0

I think a better solution could be to convert both to decimal (as one is already a Decimal) to avoid float point calculation errors. Pass the percent as a string for the same reason. Therefore this would become:

return Decimal(f'self.percent.percent') * self.amount
Alex
  • 1