MohamadHossein
MohamadHossein

Reputation: 630

Django - Model field property

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?

Upvotes: 1

Views: 1310

Answers (3)

Alex
Alex

Reputation: 1

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

Upvotes: 0

arie
arie

Reputation: 18982

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

Upvotes: 1

MohamadHossein
MohamadHossein

Reputation: 630

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)

Upvotes: 1

Related Questions