I have the number of sales and the number of returns. I need to display the percentage of non-returned items in safetycoef
. For example, there are 500 sales and 100 returns, it must be 80% in 'safetycoef'. Or 1000 sales and 240 returns, it means 76%. How to implement it?
html:
<div>
{% for phone in object_list %}
<div >
{% endif %}
<p>{{ phone.title }} — reliabilty {{phone.safetycoef }}%</p>
<p>Based on {{phone.sales }} sales and {{phone.returns }} returns </p>
</div>
{% endfor %}
</div>
CodePudding user response:
Put all your logic inside Python. The template is not the right place for this.
In your example, you're looping through multiple phones and want the percentage of the respective phone non-returned items.
I would declare a method on the model and call this inside your template:
# models.py
class Phone(models.Model):
# your attributes here
# ...
def get_reliability_percentage(self):
return (1 - (self.returns / self.sales)) * 100
Then you can call this method inside your template:
<div>
{% for phone in object_list %}
<div >
{% endif %}
<p>{{ phone.title }} — reliabilty {{ phone.get_reliability_percentage }}%</p>
<p>Based on {{phone.sales }} sales and {{phone.returns }} returns </p>
</div>
{% endfor %}
</div>
CodePudding user response:
the best way is to calculate it in the view and then send it inside the context. You can also calculate it in the html, but it's not that easy.